apply black
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 488739d · Browse files · 57 files·+3238 added−2640 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
57 files+3238 added−2640 removed
- tests:+1509 added−1352 removed
- other:+1729 added−1288 removed
Provenance
- Commit
93ba3ba- Tree
409b93e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
488739d
57 files changed+3238 added−2640 removed
modified:docs/conf.py+1 added-3 removed
45 unmodified lines46 html_show_sourcelink = False47 48 # LaTeX ----------------------------------------------------------------49 50-latex_documents = [51- (master_doc, f"Click-{version}.tex", html_title, author, "manual")52-]50+latex_documents = [(master_doc, f"Click-{version}.tex", html_title, author, "manual")]modified:examples/aliases/aliases.py+26 added-20 removed
20 unmodified lines21 def read_config(self, filename):22 parser = configparser.RawConfigParser()23 parser.read([filename])24 try:25- self.aliases.update(parser.items('aliases'))25+ self.aliases.update(parser.items("aliases"))26 except configparser.NoSectionError:27 pass28 29 def write_config(self, filename):30 parser = configparser.RawConfigParser()31- parser.add_section('aliases')31+ parser.add_section("aliases")32 for key, value in self.aliases.items():33- parser.set('aliases', key, value)34- with open(filename, 'wb') as file:33+ parser.set("aliases", key, value)34+ with open(filename, "wb") as file:35 parser.write(file)36 37 38 pass_config = click.make_pass_decorator(Config, ensure=True)22 unmodified lines61 # Alternative option: if we did not find an explicit alias we62 # allow automatic abbreviation of the command. "status" for63 # instance will match "st". We only allow that however if64 # there is only one command.65- matches = [x for x in self.list_commands(ctx)66- if x.lower().startswith(cmd_name.lower())]65+ matches = [66+ x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower())67+ ]68 if not matches:69 return None70 elif len(matches) == 1:71 return click.Group.get_command(self, ctx, matches[0])71- ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))72+ ctx.fail("Too many matches: %s" % ", ".join(sorted(matches)))73 74 75 def read_config(ctx, param, value):76 """Callback that is used whenever --config is passed. We use this to2 unmodified lines79 available.80 """81 cfg = ctx.ensure_object(Config)82 if value is None:82- value = os.path.join(os.path.dirname(__file__), 'aliases.ini')83+ value = os.path.join(os.path.dirname(__file__), "aliases.ini")84 cfg.read_config(value)85 return value86 87 88 @click.command(cls=AliasedGroup)88-@click.option('--config', type=click.Path(exists=True, dir_okay=False),89- callback=read_config, expose_value=False,90- help='The config file to use instead of the default.')89+@click.option(90+ "--config",91+ type=click.Path(exists=True, dir_okay=False),92+ callback=read_config,93+ expose_value=False,94+ help="The config file to use instead of the default.",95+)96 def cli():97 """An example application that supports aliases."""98 99 100 @cli.command()101 def push():102 """Pushes changes."""98- click.echo('Push')103+ click.echo("Push")104 105 106 @cli.command()107 def pull():108 """Pulls changes."""104- click.echo('Pull')109+ click.echo("Pull")110 111 112 @cli.command()113 def clone():114 """Clones a repository."""110- click.echo('Clone')115+ click.echo("Clone")116 117 118 @cli.command()119 def commit():120 """Commits pending changes."""116- click.echo('Commit')121+ click.echo("Commit")122 123 124 @cli.command()125 @pass_config126 def status(config):127 """Shows the status."""123- click.echo('Status for %s' % config.path)128+ click.echo("Status for %s" % config.path)129 130 131 @cli.command()132 @pass_config128-@click.argument("alias_", metavar='ALIAS', type=click.STRING)133+@click.argument("alias_", metavar="ALIAS", type=click.STRING)134 @click.argument("cmd", type=click.STRING)130-@click.option('--config_file', type=click.Path(exists=True, dir_okay=False),131- default="aliases.ini")135+@click.option(136+ "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini"137+)138 def alias(config, alias_, cmd, config_file):139 """Adds an alias to the specified configuration file."""140 config.add_alias(alias_, cmd)141 config.write_config(config_file)136- click.echo('Added %s as alias for %s' % (alias_, cmd))142+ click.echo("Added %s as alias for %s" % (alias_, cmd))modified:examples/aliases/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-aliases',5- version='1.0',6- py_modules=['aliases'],4+ name="click-example-aliases",5+ version="1.0",6+ py_modules=["aliases"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click",],9+ entry_points="""10 [console_scripts]11 aliases=aliases:cli14- ''',12+ """,13 )modified:examples/bashcompletion/bashcompletion.py+7 added-9 removed
13 unmodified lines14 if incomplete in key:15 yield key16 17 18-@cli.command(help='A command to print environment variables')18+@cli.command(help="A command to print environment variables")19 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20 def cmd1(envvar):21- click.echo('Environment variable: %s' % envvar)22- click.echo('Value: %s' % os.environ[envvar])21+ click.echo("Environment variable: %s" % envvar)22+ click.echo("Value: %s" % os.environ[envvar])23 24 25-@click.group(help='A group that holds a subcommand')25+@click.group(help="A group that holds a subcommand")26 def group():27 pass28 29 30 def list_users(ctx, args, incomplete):31 # You can generate completions with descriptions by returning32 # tuples in the form (completion, description).33- users = [('bob', 'butcher'),34- ('alice', 'baker'),35- ('jerry', 'candlestick maker')]33+ users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]34 # Ths will allow completion matches based on matches within the description string too!35 return [user for user in users if incomplete in user[0] or incomplete in user[1]]36 37 40-@group.command(help='Choose a user')38+@group.command(help="Choose a user")39 @click.argument("user", type=click.STRING, autocompletion=list_users)40 def subcmd(user):43- click.echo('Chosen user is %s' % user)41+ click.echo("Chosen user is %s" % user)42 43 44 cli.add_command(group)modified:examples/bashcompletion/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-bashcompletion',5- version='1.0',6- py_modules=['bashcompletion'],4+ name="click-example-bashcompletion",5+ version="1.0",6+ py_modules=["bashcompletion"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click",],9+ entry_points="""10 [console_scripts]11 bashcompletion=bashcompletion:cli14- ''',12+ """,13 )modified:examples/colors/colors.py+25 added-11 removed
1 import click2 3 4-all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \5- 'cyan', 'white', 'bright_black', 'bright_red', \6- 'bright_green', 'bright_yellow', 'bright_blue', \7- 'bright_magenta', 'bright_cyan', 'bright_white'4+all_colors = (5+ "black",6+ "red",7+ "green",8+ "yellow",9+ "blue",10+ "magenta",11+ "cyan",12+ "white",13+ "bright_black",14+ "bright_red",15+ "bright_green",16+ "bright_yellow",17+ "bright_blue",18+ "bright_magenta",19+ "bright_cyan",20+ "bright_white",21+)22 23 24 @click.command()25 def cli():3 unmodified lines29 30 Give it a try!31 """32 for color in all_colors:19- click.echo(click.style('I am colored %s' % color, fg=color))33+ click.echo(click.style("I am colored %s" % color, fg=color))34 for color in all_colors:21- click.echo(click.style('I am colored %s and bold' % color,22- fg=color, bold=True))35+ click.echo(click.style("I am colored %s and bold" % color, fg=color, bold=True))36 for color in all_colors:24- click.echo(click.style('I am reverse colored %s' % color, fg=color,25- reverse=True))37+ click.echo(38+ click.style("I am reverse colored %s" % color, fg=color, reverse=True)39+ )40 27- click.echo(click.style('I am blinking', blink=True))28- click.echo(click.style('I am underlined', underline=True))41+ click.echo(click.style("I am blinking", blink=True))42+ click.echo(click.style("I am underlined", underline=True))modified:examples/colors/setup.py+7 added-7 removed
1 from setuptools import setup2 3 setup(4- name='click-example-colors',5- version='1.0',6- py_modules=['colors'],4+ name="click-example-colors",5+ version="1.0",6+ py_modules=["colors"],7 include_package_data=True,8 install_requires=[9- 'click',9+ "click",10 # Colorama is only required for Windows.11- 'colorama',11+ "colorama",12 ],13- entry_points='''13+ entry_points="""14 [console_scripts]15 colors=colors:cli16- ''',16+ """,17 )modified:examples/complex/complex/commands/cmd_init.py+3 added-4 removed
1 unmodified line2 3 import click4 5 6-@click.command('init', short_help='Initializes a repo.')7-@click.argument('path', required=False, type=click.Path(resolve_path=True))6+@click.command("init", short_help="Initializes a repo.")7+@click.argument("path", required=False, type=click.Path(resolve_path=True))8 @pass_environment9 def cli(ctx, path):10 """Initializes a repository."""11 if path is None:12 path = ctx.home13- ctx.log('Initialized the repository in %s',14- click.format_filename(path))13+ ctx.log("Initialized the repository in %s", click.format_filename(path))modified:examples/complex/complex/commands/cmd_status.py+3 added-3 removed
1 unmodified line2 3 import click4 5 6-@click.command('status', short_help='Shows file changes.')6+@click.command("status", short_help="Shows file changes.")7 @pass_environment8 def cli(ctx):9 """Shows file changes in the current working directory."""10- ctx.log('Changed files: none')11- ctx.vlog('bla bla bla, debug info')10+ ctx.log("Changed files: none")11+ ctx.vlog("bla bla bla, debug info")modified:examples/complex/complex/cli.py+11 added-15 removed
2 unmodified lines3 4 import click5 6 7-CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')7+CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")8 9 10 class Environment(object):11-11 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()14 9 unmodified lines24 self.log(msg, *args)25 26 27 pass_environment = click.make_pass_decorator(Environment, ensure=True)29-cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),30- 'commands'))28+cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))29 30 31 class ComplexCLI(click.MultiCommand):34-32 def list_commands(self, ctx):33 rv = []34 for filename in os.listdir(cmd_folder):38- if filename.endswith('.py') and \39- filename.startswith('cmd_'):35+ if filename.endswith(".py") and filename.startswith("cmd_"):36 rv.append(filename[4:-3])37 rv.sort()38 return rv39 40 def get_command(self, ctx, name):41 try:42 if sys.version_info[0] == 2:47- name = name.encode('ascii', 'replace')48- mod = __import__('complex.commands.cmd_' + name,49- None, None, ['cli'])43+ name = name.encode("ascii", "replace")44+ mod = __import__("complex.commands.cmd_" + name, None, None, ["cli"])45 except ImportError:46 return47 return mod.cli48 49 50 @click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)56-@click.option('--home', type=click.Path(exists=True, file_okay=False,57- resolve_path=True),58- help='Changes the folder to operate on.')59-@click.option('-v', '--verbose', is_flag=True,60- help='Enables verbose mode.')51+@click.option(52+ "--home",53+ type=click.Path(exists=True, file_okay=False, resolve_path=True),54+ help="Changes the folder to operate on.",55+)56+@click.option("-v", "--verbose", is_flag=True, help="Enables verbose mode.")57 @pass_environment58 def cli(ctx, verbose, home):59 """A complex command line interface."""60 ctx.verbose = verbose2 unmodified linesmodified:examples/complex/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-complex',5- version='1.0',6- packages=['complex', 'complex.commands'],4+ name="click-example-complex",5+ version="1.0",6+ packages=["complex", "complex.commands"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click",],9+ entry_points="""10 [console_scripts]11 complex=complex.cli:cli14- ''',12+ """,13 )modified:examples/imagepipe/imagepipe.py+70 added-49 removed
41 unmodified lines42 def processor(f):43 """Helper decorator to rewrite a function so that it returns another44 function from it.45 """46+47 def new_func(*args, **kwargs):48 def processor(stream):49 return f(stream, *args, **kwargs)50+51 return processor52+53 return update_wrapper(new_func, f)54 55 56 def generator(f):57 """Similar to the :func:`processor` but passes through old values58 unchanged and does not pass through the values as parameter.59 """60+61 @processor62 def new_func(stream, *args, **kwargs):63 for item in stream:64 yield item65 for item in f(*args, **kwargs):66 yield item67+68 return update_wrapper(new_func, f)69 70 71 def copy_filename(new, old):72 new.filename = old.filename73 return new74 75 71-@cli.command('open')72-@click.option('-i', '--image', 'images', type=click.Path(),73- multiple=True, help='The image file to open.')76+@cli.command("open")77+@click.option(78+ "-i",79+ "--image",80+ "images",81+ type=click.Path(),82+ multiple=True,83+ help="The image file to open.",84+)85 @generator86 def open_cmd(images):87 """Loads one or multiple images for processing. The input parameter88 can be specified multiple times to load more than one image.89 """90 for image in images:91 try:92 click.echo('Opening "%s"' % image)82- if image == '-':93+ if image == "-":94 img = Image.open(click.get_binary_stdin())84- img.filename = '-'95+ img.filename = "-"96 else:97 img = Image.open(image)98 yield img99 except Exception as e:100 click.echo('Could not open image "%s": %s' % (image, e), err=True)101 102 92-@cli.command('save')93-@click.option('--filename', default='processed-%04d.png', type=click.Path(),94- help='The format for the filename.',95- show_default=True)103+@cli.command("save")104+@click.option(105+ "--filename",106+ default="processed-%04d.png",107+ type=click.Path(),108+ help="The format for the filename.",109+ show_default=True,110+)111 @processor112 def save_cmd(images, filename):113 """Saves all processed images to a series of files."""114 for idx, image in enumerate(images):1 unmodified line116 fn = filename % (idx + 1)117 click.echo('Saving "%s" as "%s"' % (image.filename, fn))118 yield image.save(fn)119 except Exception as e:105- click.echo('Could not save image "%s": %s' %106- (image.filename, e), err=True)120+ click.echo('Could not save image "%s": %s' % (image.filename, e), err=True)121 122 109-@cli.command('display')123+@cli.command("display")124 @processor125 def display_cmd(images):126 """Opens all images in an image viewer."""127 for image in images:1 unmodified line129 image.show()130 yield image131 132 119-@cli.command('resize')120-@click.option('-w', '--width', type=int, help='The new width of the image.')121-@click.option('-h', '--height', type=int, help='The new height of the image.')133+@cli.command("resize")134+@click.option("-w", "--width", type=int, help="The new width of the image.")135+@click.option("-h", "--height", type=int, help="The new height of the image.")136 @processor137 def resize_cmd(images, width, height):138 """Resizes an image by fitting it into the box without changing139 the aspect ratio.4 unmodified lines144 image.thumbnail((w, h))145 yield image146 147 134-@cli.command('crop')135-@click.option('-b', '--border', type=int, help='Crop the image from all '136- 'sides by this amount.')148+@cli.command("crop")149+@click.option(150+ "-b", "--border", type=int, help="Crop the image from all sides by this amount."151+)152 @processor153 def crop_cmd(images, border):154 """Crops an image from all edges."""155 for image in images:11 unmodified lines167 def convert_rotation(ctx, param, value):168 if value is None:169 return170 value = value.lower()156- if value in ('90', 'r', 'right'):171+ if value in ("90", "r", "right"):172 return (Image.ROTATE_90, 90)158- if value in ('180', '-180'):173+ if value in ("180", "-180"):174 return (Image.ROTATE_180, 180)160- if value in ('-90', '270', 'l', 'left'):175+ if value in ("-90", "270", "l", "left"):176 return (Image.ROTATE_270, 270)177 raise click.BadParameter('invalid rotation "%s"' % value)178 179 180 def convert_flip(ctx, param, value):181 if value is None:182 return183 value = value.lower()169- if value in ('lr', 'leftright'):170- return (Image.FLIP_LEFT_RIGHT, 'left to right')171- if value in ('tb', 'topbottom', 'upsidedown', 'ud'):172- return (Image.FLIP_LEFT_RIGHT, 'top to bottom')184+ if value in ("lr", "leftright"):185+ return (Image.FLIP_LEFT_RIGHT, "left to right")186+ if value in ("tb", "topbottom", "upsidedown", "ud"):187+ return (Image.FLIP_LEFT_RIGHT, "top to bottom")188 raise click.BadParameter('invalid flip "%s"' % value)189 190 176-@cli.command('transpose')177-@click.option('-r', '--rotate', callback=convert_rotation,178- help='Rotates the image (in degrees)')179-@click.option('-f', '--flip', callback=convert_flip,180- help='Flips the image [LR / TB]')191+@cli.command("transpose")192+@click.option(193+ "-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)"194+)195+@click.option("-f", "--flip", callback=convert_flip, help="Flips the image [LR / TB]")196 @processor197 def transpose_cmd(images, rotate, flip):198 """Transposes an image by either rotating or flipping it."""199 for image in images:7 unmodified lines207 image = copy_filename(image.transpose(mode), image)208 yield image209 210 196-@cli.command('blur')197-@click.option('-r', '--radius', default=2, show_default=True,198- help='The blur radius.')211+@cli.command("blur")212+@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")213 @processor214 def blur_cmd(images, radius):215 """Applies gaussian blur."""216 blur = ImageFilter.GaussianBlur(radius)1 unmodified line218 click.echo('Blurring "%s" by %dpx' % (image.filename, radius))219 yield copy_filename(image.filter(blur), image)220 221 208-@cli.command('smoothen')209-@click.option('-i', '--iterations', default=1, show_default=True,210- help='How many iterations of the smoothen filter to run.')222+@cli.command("smoothen")223+@click.option(224+ "-i",225+ "--iterations",226+ default=1,227+ show_default=True,228+ help="How many iterations of the smoothen filter to run.",229+)230 @processor231 def smoothen_cmd(images, iterations):232 """Applies a smoothening filter."""233 for image in images:215- click.echo('Smoothening "%s" %d time%s' %216- (image.filename, iterations, iterations != 1 and 's' or '',))234+ click.echo(235+ 'Smoothening "%s" %d time%s'236+ % (image.filename, iterations, iterations != 1 and "s" or "",)237+ )238 for x in xrange(iterations):239 image = copy_filename(image.filter(ImageFilter.BLUR), image)240 yield image241 242 222-@cli.command('emboss')243+@cli.command("emboss")244 @processor245 def emboss_cmd(images):246 """Embosses an image."""247 for image in images:248 click.echo('Embossing "%s"' % image.filename)249 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)250 251 231-@cli.command('sharpen')232-@click.option('-f', '--factor', default=2.0,233- help='Sharpens the image.', show_default=True)252+@cli.command("sharpen")253+@click.option(254+ "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True255+)256 @processor257 def sharpen_cmd(images, factor):258 """Sharpens an image."""259 for image in images:1 unmodified line261 enhancer = ImageEnhance.Sharpness(image)262 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)263 264 243-@cli.command('paste')244-@click.option('-l', '--left', default=0, help='Offset from left.')245-@click.option('-r', '--right', default=0, help='Offset from right.')265+@cli.command("paste")266+@click.option("-l", "--left", default=0, help="Offset from left.")267+@click.option("-r", "--right", default=0, help="Offset from right.")268 @processor269 def paste_cmd(images, left, right):270 """Pastes the second image on the first image and leaves the rest271 unchanged.6 unmodified lines278 if image is not None:279 yield image280 return281 260- click.echo('Paste "%s" on "%s"' %261- (to_paste.filename, image.filename))282+ click.echo('Paste "%s" on "%s"' % (to_paste.filename, image.filename))283 mask = None263- if to_paste.mode == 'RGBA' or 'transparency' in to_paste.info:284+ if to_paste.mode == "RGBA" or "transparency" in to_paste.info:285 mask = to_paste286 image.paste(to_paste, (left, right), mask)266- image.filename += '+' + to_paste.filename287+ image.filename += "+" + to_paste.filename288 yield image289 290 for image in imageiter:291 yield imagemodified:examples/imagepipe/setup.py+6 added-9 removed
1 from setuptools import setup2 3 setup(4- name='click-example-imagepipe',5- version='1.0',6- py_modules=['imagepipe'],4+ name="click-example-imagepipe",5+ version="1.0",6+ py_modules=["imagepipe"],7 include_package_data=True,8- install_requires=[9- 'click',10- 'pillow',11- ],12- entry_points='''8+ install_requires=["click", "pillow",],9+ entry_points="""10 [console_scripts]11 imagepipe=imagepipe:cli15- ''',12+ """,13 )modified:examples/inout/inout.py+2 added-2 removed
1 import click2 3 4 @click.command()5-@click.argument('input', type=click.File('rb'), nargs=-1)6-@click.argument('output', type=click.File('wb'))5+@click.argument("input", type=click.File("rb"), nargs=-1)6+@click.argument("output", type=click.File("wb"))7 def cli(input, output):8 """This script works similar to the Unix `cat` command but it writes9 into a specific file (which could be the standard output as denoted by10 the ``-`` sign).20 unmodified linesmodified:examples/inout/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-inout',5- version='0.1',6- py_modules=['inout'],4+ name="click-example-inout",5+ version="0.1",6+ py_modules=["inout"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click",],9+ entry_points="""10 [console_scripts]11 inout=inout:cli14- ''',12+ """,13 )modified:examples/naval/naval.py+31 added-29 removed
15 unmodified lines16 def ship():17 """Manages ships."""18 19 20-@ship.command('new')21-@click.argument('name')20+@ship.command("new")21+@click.argument("name")22 def ship_new(name):23 """Creates a new ship."""24- click.echo('Created ship %s' % name)24+ click.echo("Created ship %s" % name)25 26 27-@ship.command('move')28-@click.argument('ship')29-@click.argument('x', type=float)30-@click.argument('y', type=float)31-@click.option('--speed', metavar='KN', default=10,32- help='Speed in knots.')27+@ship.command("move")28+@click.argument("ship")29+@click.argument("x", type=float)30+@click.argument("y", type=float)31+@click.option("--speed", metavar="KN", default=10, help="Speed in knots.")32 def ship_move(ship, x, y, speed):33 """Moves SHIP to the new location X,Y."""35- click.echo('Moving ship %s to %s,%s with speed %s' % (ship, x, y, speed))34+ click.echo("Moving ship %s to %s,%s with speed %s" % (ship, x, y, speed))35 36 38-@ship.command('shoot')39-@click.argument('ship')40-@click.argument('x', type=float)41-@click.argument('y', type=float)37+@ship.command("shoot")38+@click.argument("ship")39+@click.argument("x", type=float)40+@click.argument("y", type=float)41 def ship_shoot(ship, x, y):42 """Makes SHIP fire to X,Y."""44- click.echo('Ship %s fires to %s,%s' % (ship, x, y))43+ click.echo("Ship %s fires to %s,%s" % (ship, x, y))44 45 47-@cli.group('mine')46+@cli.group("mine")47 def mine():48 """Manages mines."""49 50 52-@mine.command('set')53-@click.argument('x', type=float)54-@click.argument('y', type=float)55-@click.option('ty', '--moored', flag_value='moored',56- default=True,57- help='Moored (anchored) mine. Default.')58-@click.option('ty', '--drifting', flag_value='drifting',59- help='Drifting mine.')51+@mine.command("set")52+@click.argument("x", type=float)53+@click.argument("y", type=float)54+@click.option(55+ "ty",56+ "--moored",57+ flag_value="moored",58+ default=True,59+ help="Moored (anchored) mine. Default.",60+)61+@click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.")62 def mine_set(x, y, ty):63 """Sets a mine at a specific coordinate."""62- click.echo('Set %s mine at %s,%s' % (ty, x, y))64+ click.echo("Set %s mine at %s,%s" % (ty, x, y))65 66 65-@mine.command('remove')66-@click.argument('x', type=float)67-@click.argument('y', type=float)67+@mine.command("remove")68+@click.argument("x", type=float)69+@click.argument("y", type=float)70 def mine_remove(x, y):71 """Removes a mine at a specific coordinate."""70- click.echo('Removed mine at %s,%s' % (x, y))72+ click.echo("Removed mine at %s,%s" % (x, y))modified:examples/naval/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-naval',5- version='2.0',6- py_modules=['naval'],4+ name="click-example-naval",5+ version="2.0",6+ py_modules=["naval"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click",],9+ entry_points="""10 [console_scripts]11 naval=naval:cli14- ''',12+ """,13 )modified:examples/repo/repo.py+65 added-50 removed
4 unmodified lines5 import click6 7 8 class Repo(object):9-9 def __init__(self, home):10 self.home = home11 self.config = {}12 self.verbose = False13 14 def set_config(self, key, value):15 self.config[key] = value16 if self.verbose:18- click.echo(' config[%s] = %s' % (key, value), file=sys.stderr)17+ click.echo(" config[%s] = %s" % (key, value), file=sys.stderr)18 19 def __repr__(self):21- return '<Repo %r>' % self.home20+ return "<Repo %r>" % self.home21 22 23 pass_repo = click.make_pass_decorator(Repo)24 25 26 @click.group()28-@click.option('--repo-home', envvar='REPO_HOME', default='.repo',29- metavar='PATH', help='Changes the repository folder location.')30-@click.option('--config', nargs=2, multiple=True,31- metavar='KEY VALUE', help='Overrides a config key/value pair.')32-@click.option('--verbose', '-v', is_flag=True,33- help='Enables verbose mode.')34-@click.version_option('1.0')27+@click.option(28+ "--repo-home",29+ envvar="REPO_HOME",30+ default=".repo",31+ metavar="PATH",32+ help="Changes the repository folder location.",33+)34+@click.option(35+ "--config",36+ nargs=2,37+ multiple=True,38+ metavar="KEY VALUE",39+ help="Overrides a config key/value pair.",40+)41+@click.option("--verbose", "-v", is_flag=True, help="Enables verbose mode.")42+@click.version_option("1.0")43 @click.pass_context44 def cli(ctx, repo_home, config, verbose):45 """Repo is a command line tool that showcases how to build complex46 command line interfaces with Click.10 unmodified lines57 ctx.obj.set_config(key, value)58 59 60 @cli.command()53-@click.argument('src')54-@click.argument('dest', required=False)55-@click.option('--shallow/--deep', default=False,56- help='Makes a checkout shallow or deep. Deep by default.')57-@click.option('--rev', '-r', default='HEAD',58- help='Clone a specific revision instead of HEAD.')61+@click.argument("src")62+@click.argument("dest", required=False)63+@click.option(64+ "--shallow/--deep",65+ default=False,66+ help="Makes a checkout shallow or deep. Deep by default.",67+)68+@click.option(69+ "--rev", "-r", default="HEAD", help="Clone a specific revision instead of HEAD."70+)71 @pass_repo72 def clone(repo, src, dest, shallow, rev):73 """Clones a repository.74 1 unmodified line76 is not provided this will automatically use the last path component77 of SRC and create that folder.78 """79 if dest is None:68- dest = posixpath.split(src)[-1] or '.'69- click.echo('Cloning repo %s to %s' % (src, os.path.abspath(dest)))80+ dest = posixpath.split(src)[-1] or "."81+ click.echo("Cloning repo %s to %s" % (src, os.path.abspath(dest)))82 repo.home = dest83 if shallow:72- click.echo('Making shallow checkout')73- click.echo('Checking out revision %s' % rev)84+ click.echo("Making shallow checkout")85+ click.echo("Checking out revision %s" % rev)86 87 88 @cli.command()89 @click.confirmation_option()2 unmodified lines92 """Deletes a repository.93 94 This will throw away the current repository.95 """84- click.echo('Destroying repo %s' % repo.home)85- click.echo('Deleted!')96+ click.echo("Destroying repo %s" % repo.home)97+ click.echo("Deleted!")98 99 100 @cli.command()89-@click.option('--username', prompt=True,90- help='The developer\'s shown username.')91-@click.option('--email', prompt='E-Mail',92- help='The developer\'s email address')93-@click.password_option(help='The login password.')101+@click.option("--username", prompt=True, help="The developer's shown username.")102+@click.option("--email", prompt="E-Mail", help="The developer's email address")103+@click.password_option(help="The login password.")104 @pass_repo105 def setuser(repo, username, email, password):106 """Sets the user credentials.107 108 This will override the current user config.109 """100- repo.set_config('username', username)101- repo.set_config('email', email)102- repo.set_config('password', '*' * len(password))103- click.echo('Changed credentials.')110+ repo.set_config("username", username)111+ repo.set_config("email", email)112+ repo.set_config("password", "*" * len(password))113+ click.echo("Changed credentials.")114 115 116 @cli.command()107-@click.option('--message', '-m', multiple=True,108- help='The commit message. If provided multiple times each '109- 'argument gets converted into a new line.')110-@click.argument('files', nargs=-1, type=click.Path())117+@click.option(118+ "--message",119+ "-m",120+ multiple=True,121+ help="The commit message. If provided multiple times each "122+ "argument gets converted into a new line.",123+)124+@click.argument("files", nargs=-1, type=click.Path())125 @pass_repo126 def commit(repo, files, message):127 """Commits outstanding changes.128 3 unmodified lines132 If a list of files is omitted, all changes reported by "repo status"133 will be committed.134 """135 if not message:122- marker = '# Files to be committed:'123- hint = ['', '', marker, '#']136+ marker = "# Files to be committed:"137+ hint = ["", "", marker, "#"]138 for file in files:125- hint.append('# U %s' % file)126- message = click.edit('\n'.join(hint))139+ hint.append("# U %s" % file)140+ message = click.edit("\n".join(hint))141 if message is None:128- click.echo('Aborted!')142+ click.echo("Aborted!")143 return144 msg = message.split(marker)[0].rstrip()145 if not msg:132- click.echo('Aborted! Empty commit message')146+ click.echo("Aborted! Empty commit message")147 return148 else:135- msg = '\n'.join(message)136- click.echo('Files to be committed: %s' % (files,))137- click.echo('Commit message:\n' + msg)149+ msg = "\n".join(message)150+ click.echo("Files to be committed: %s" % (files,))151+ click.echo("Commit message:\n" + msg)152 153 140-@cli.command(short_help='Copies files.')141-@click.option('--force', is_flag=True,142- help='forcibly copy over an existing managed file')143-@click.argument('src', nargs=-1, type=click.Path())144-@click.argument('dst', type=click.Path())154+@cli.command(short_help="Copies files.")155+@click.option(156+ "--force", is_flag=True, help="forcibly copy over an existing managed file"157+)158+@click.argument("src", nargs=-1, type=click.Path())159+@click.argument("dst", type=click.Path())160 @pass_repo161 def copy(repo, src, dst, force):162 """Copies one or multiple files to a new location. This copies all163 files from SRC to DST.164 """165 for fn in src:151- click.echo('Copy from %s -> %s' % (fn, dst))166+ click.echo("Copy from %s -> %s" % (fn, dst))modified:examples/repo/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-repo',5- version='0.1',6- py_modules=['repo'],4+ name="click-example-repo",5+ version="0.1",6+ py_modules=["repo"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click",],9+ entry_points="""10 [console_scripts]11 repo=repo:cli14- ''',12+ """,13 )modified:examples/termui/setup.py+7 added-7 removed
1 from setuptools import setup2 3 setup(4- name='click-example-termui',5- version='1.0',6- py_modules=['termui'],4+ name="click-example-termui",5+ version="1.0",6+ py_modules=["termui"],7 include_package_data=True,8 install_requires=[9- 'click',9+ "click",10 # Colorama is only required for Windows.11- 'colorama',11+ "colorama",12 ],13- entry_points='''13+ entry_points="""14 [console_scripts]15 termui=termui:cli16- ''',16+ """,17 )modified:examples/termui/termui.py+67 added-49 removed
13 unmodified lines14 15 @cli.command()16 def colordemo():17 """Demonstrates ANSI color support."""18- for color in 'red', 'green', 'blue':19- click.echo(click.style('I am colored %s' % color, fg=color))20- click.echo(click.style('I am background colored %s' % color, bg=color))18+ for color in "red", "green", "blue":19+ click.echo(click.style("I am colored %s" % color, fg=color))20+ click.echo(click.style("I am background colored %s" % color, bg=color))21 22 23 @cli.command()24 def pager():25 """Demonstrates using the pager."""26 lines = []27 for x in range(200):28- lines.append('%s. Hello World!' % click.style(str(x), fg='green'))29- click.echo_via_pager('\n'.join(lines))28+ lines.append("%s. Hello World!" % click.style(str(x), fg="green"))29+ click.echo_via_pager("\n".join(lines))30 31 32 @cli.command()33-@click.option('--count', default=8000, type=click.IntRange(1, 100000),34- help='The number of items to process.')33+@click.option(34+ "--count",35+ default=8000,36+ type=click.IntRange(1, 100000),37+ help="The number of items to process.",38+)39 def progress(count):40 """Demonstrates the progress bar."""41 items = range(count)42 4 unmodified lines47 for item in items:48 if random.random() > 0.3:49 yield item50 47- with click.progressbar(items, label='Processing accounts',48- fill_char=click.style('#', fg='green')) as bar:51+ with click.progressbar(52+ items, label="Processing accounts", fill_char=click.style("#", fg="green")53+ ) as bar:54 for item in bar:55 process_slowly(item)56 57 def show_item(item):58 if item is not None:54- return 'Item #%d' % item59+ return "Item #%d" % item60 56- with click.progressbar(filter(items), label='Committing transaction',57- fill_char=click.style('#', fg='yellow'),58- item_show_func=show_item) as bar:61+ with click.progressbar(62+ filter(items),63+ label="Committing transaction",64+ fill_char=click.style("#", fg="yellow"),65+ item_show_func=show_item,66+ ) as bar:67 for item in bar:68 process_slowly(item)69 62- with click.progressbar(length=count, label='Counting',63- bar_template='%(label)s %(bar)s | %(info)s',64- fill_char=click.style(u'█', fg='cyan'),65- empty_char=' ') as bar:70+ with click.progressbar(71+ length=count,72+ label="Counting",73+ bar_template="%(label)s %(bar)s | %(info)s",74+ fill_char=click.style(u"█", fg="cyan"),75+ empty_char=" ",76+ ) as bar:77 for item in bar:78 process_slowly(item)79 69- with click.progressbar(length=count, width=0, show_percent=False,70- show_eta=False,71- fill_char=click.style('#', fg='magenta')) as bar:80+ with click.progressbar(81+ length=count,82+ width=0,83+ show_percent=False,84+ show_eta=False,85+ fill_char=click.style("#", fg="magenta"),86+ ) as bar:87 for item in bar:88 process_slowly(item)89 90 # 'Non-linear progress bar'76- steps = [math.exp( x * 1. / 20) - 1 for x in range(20)]91+ steps = [math.exp(x * 1.0 / 20) - 1 for x in range(20)]92 count = int(sum(steps))78- with click.progressbar(length=count, show_percent=False,79- label='Slowing progress bar',80- fill_char=click.style(u'█', fg='green')) as bar:93+ with click.progressbar(94+ length=count,95+ show_percent=False,96+ label="Slowing progress bar",97+ fill_char=click.style(u"█", fg="green"),98+ ) as bar:99 for item in steps:100 time.sleep(item)101 bar.update(item)102 103 104 @cli.command()87-@click.argument('url')105+@click.argument("url")106 def open(url):107 """Opens a file or URL In the default application."""108 click.launch(url)109 110 111 @cli.command()94-@click.argument('url')112+@click.argument("url")113 def locate(url):114 """Opens a file or URL In the default application."""115 click.launch(url, locate=True)116 117 118 @cli.command()119 def edit():120 """Opens an editor with some text in it."""103- MARKER = '# Everything below is ignored\n'104- message = click.edit('\n\n' + MARKER)121+ MARKER = "# Everything below is ignored\n"122+ message = click.edit("\n\n" + MARKER)123 if message is not None:106- msg = message.split(MARKER, 1)[0].rstrip('\n')124+ msg = message.split(MARKER, 1)[0].rstrip("\n")125 if not msg:108- click.echo('Empty message!')126+ click.echo("Empty message!")127 else:110- click.echo('Message:\n' + msg)128+ click.echo("Message:\n" + msg)129 else:112- click.echo('You did not enter anything!')130+ click.echo("You did not enter anything!")131 132 133 @cli.command()134 def clear():9 unmodified lines144 145 @cli.command()146 def menu():147 """Shows a simple menu."""130- menu = 'main'148+ menu = "main"149 while 1:132- if menu == 'main':133- click.echo('Main menu:')134- click.echo(' d: debug menu')135- click.echo(' q: quit')150+ if menu == "main":151+ click.echo("Main menu:")152+ click.echo(" d: debug menu")153+ click.echo(" q: quit")154 char = click.getchar()137- if char == 'd':138- menu = 'debug'139- elif char == 'q':140- menu = 'quit'155+ if char == "d":156+ menu = "debug"157+ elif char == "q":158+ menu = "quit"159 else:142- click.echo('Invalid input')143- elif menu == 'debug':144- click.echo('Debug menu')145- click.echo(' b: back')160+ click.echo("Invalid input")161+ elif menu == "debug":162+ click.echo("Debug menu")163+ click.echo(" b: back")164 char = click.getchar()147- if char == 'b':148- menu = 'main'165+ if char == "b":166+ menu = "main"167 else:150- click.echo('Invalid input')151- elif menu == 'quit':168+ click.echo("Invalid input")169+ elif menu == "quit":170 returnmodified:examples/validation/setup.py+6 added-8 removed
1 from setuptools import setup2 3 setup(4- name='click-example-validation',5- version='1.0',6- py_modules=['validation'],4+ name="click-example-validation",5+ version="1.0",6+ py_modules=["validation"],7 include_package_data=True,8- install_requires=[9- 'click',10- ],11- entry_points='''8+ install_requires=["click",],9+ entry_points="""10 [console_scripts]11 validation=validation:cli14- ''',12+ """,13 )modified:examples/validation/validation.py+22 added-15 removed
6 unmodified lines7 8 9 def validate_count(ctx, param, value):10 if value < 0 or value % 2 != 0:11- raise click.BadParameter('Should be a positive, even integer.')11+ raise click.BadParameter("Should be a positive, even integer.")12 return value13 14 15 class URL(click.ParamType):16- name = 'url'16+ name = "url"17 18 def convert(self, value, param, ctx):19 if not isinstance(value, tuple):20 value = urlparse.urlparse(value)21- if value.scheme not in ('http', 'https'):22- self.fail('invalid URL scheme (%s). Only HTTP URLs are '23- 'allowed' % value.scheme, param, ctx)21+ if value.scheme not in ("http", "https"):22+ self.fail(23+ "invalid URL scheme (%s). Only HTTP URLs are "24+ "allowed" % value.scheme,25+ param,26+ ctx,27+ )28 return value29 30 31 @click.command()28-@click.option('--count', default=2, callback=validate_count,29- help='A positive even number.')30-@click.option('--foo', help='A mysterious parameter.')31-@click.option('--url', help='A URL', type=URL())32+@click.option(33+ "--count", default=2, callback=validate_count, help="A positive even number."34+)35+@click.option("--foo", help="A mysterious parameter.")36+@click.option("--url", help="A URL", type=URL())37 @click.version_option()38 def cli(count, foo, url):39 """Validation.40 41 This example validates parameters in different ways. It does it42 through callbacks, through a custom type as well as by validating43 manually in the function.44 """40- if foo is not None and foo != 'wat':41- raise click.BadParameter('If a value is provided it needs to be the '42- 'value "wat".', param_hint=['--foo'])43- click.echo('count: %s' % count)44- click.echo('foo: %s' % foo)45- click.echo('url: %s' % repr(url))45+ if foo is not None and foo != "wat":46+ raise click.BadParameter(47+ 'If a value is provided it needs to be the value "wat".',48+ param_hint=["--foo"],49+ )50+ click.echo("count: %s" % count)51+ click.echo("foo: %s" % foo)52+ click.echo("url: %s" % repr(url))modified:src/click/__init__.py+1 added-1 removed
74 unmodified lines75 # Controls if click should emit the warning about the use of unicode76 # literals.77 disable_unicode_literals_warning = False78 79-__version__ = '7.1.dev'79+__version__ = "7.1.dev"modified:src/click/_bashcomplete.py+72 added-43 removed
12 unmodified lines13 from collections import abc14 except ImportError:15 import collections as abc16 17-WORDBREAK = '='17+WORDBREAK = "="18 19 # Note, only BASH version 4.4 and later have the nosort option.20-COMPLETION_SCRIPT_BASH = '''20+COMPLETION_SCRIPT_BASH = """21 %(complete_func)s() {22 local IFS=$'\n'23 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\24 COMP_CWORD=$COMP_CWORD \\12 unmodified lines37 complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s38 }39 40 %(complete_func)setup41-'''41+"""42 43-COMPLETION_SCRIPT_ZSH = '''43+COMPLETION_SCRIPT_ZSH = """44 #compdef %(script_names)s45 46 %(complete_func)s() {47 local -a completions24 unmodified lines72 compstate[insert]="automenu"73 }74 75 compdef %(complete_func)s %(script_names)s76-'''76+"""77 78-COMPLETION_SCRIPT_FISH = '''78+COMPLETION_SCRIPT_FISH = """79 complete --no-files --command %(script_names)s --arguments "(env %(autocomplete_var)s=complete_fish COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) %(script_names)s)"80-'''80+"""81 82 _completion_scripts = {83 "bash": COMPLETION_SCRIPT_BASH,84 "zsh": COMPLETION_SCRIPT_ZSH,85 "fish": COMPLETION_SCRIPT_FISH,86 }87 88-_invalid_ident_char_re = re.compile(r'[^a-zA-Z0-9_]')88+_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")89 90 91 def get_completion_script(prog_name, complete_var, shell):92- cf_name = _invalid_ident_char_re.sub('', prog_name.replace('-', '_'))92+ cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))93 script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)94- return (script % {95- 'complete_func': '_%s_completion' % cf_name,96- 'script_names': prog_name,97- 'autocomplete_var': complete_var,98- }).strip() + ';'94+ return (95+ script96+ % {97+ "complete_func": "_%s_completion" % cf_name,98+ "script_names": prog_name,99+ "autocomplete_var": complete_var,100+ }101+ ).strip() + ";"102 103 104 def resolve_ctx(cli, prog_name, args):105 """10 unmodified lines116 if not ctx.command.chain:117 cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)118 if cmd is None:119 return ctx117- ctx = cmd.make_context(cmd_name, args, parent=ctx,118- resilient_parsing=True)120+ ctx = cmd.make_context(121+ cmd_name, args, parent=ctx, resilient_parsing=True122+ )123 args = ctx.protected_args + ctx.args124 else:125 # Walk chained subcommand contexts saving the last one.126 while args:127 cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)128 if cmd is None:129 return ctx130+ sub_ctx = cmd.make_context(131+ cmd_name,132+ args,126- sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,127- allow_extra_args=True,128- allow_interspersed_args=False,129- resilient_parsing=True)133+ parent=ctx,134+ allow_extra_args=True,135+ allow_interspersed_args=False,136+ resilient_parsing=True,137+ )138 args = sub_ctx.args139 ctx = sub_ctx140 args = sub_ctx.protected_args + sub_ctx.args141 else:5 unmodified lines147 """148 :param param_str: param_str to check149 :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")150 """143- return param_str and param_str[:1] == '-'151+ return param_str and param_str[:1] == "-"152 153 154 def is_incomplete_option(all_args, cmd_param):155 """7 unmodified lines163 return False164 if cmd_param.is_flag:165 return False166 last_option = None159- for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])):167+ for index, arg_str in enumerate(168+ reversed([arg for arg in all_args if arg != WORDBREAK])169+ ):170 if index + 1 > cmd_param.nargs:171 break172 if start_of_option(arg_str):173 last_option = arg_str14 unmodified lines188 if current_param_values is None:189 return True190 if cmd_param.nargs == -1:191 return True182- if isinstance(current_param_values, abc.Iterable) \183- and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:192+ if (193+ isinstance(current_param_values, abc.Iterable)194+ and cmd_param.nargs > 1195+ and len(current_param_values) < cmd_param.nargs196+ ):197 return True198 return False199 200 7 unmodified lines208 """209 results = []210 if isinstance(cmd_param.type, Choice):211 # Choices don't support descriptions.199- results = [(c, None)200- for c in cmd_param.type.choices if str(c).startswith(incomplete)]212+ results = [213+ (c, None) for c in cmd_param.type.choices if str(c).startswith(incomplete)214+ ]215 elif cmd_param.autocompletion is not None:202- dynamic_completions = cmd_param.autocompletion(ctx=ctx,203- args=args,204- incomplete=incomplete)205- results = [c if isinstance(c, tuple) else (c, None)206- for c in dynamic_completions]216+ dynamic_completions = cmd_param.autocompletion(217+ ctx=ctx, args=args, incomplete=incomplete218+ )219+ results = [220+ c if isinstance(c, tuple) else (c, None) for c in dynamic_completions221+ ]222 return results223 224 225 def get_visible_commands_starting_with(ctx, starts_with):12 unmodified lines238 def add_subcommand_completions(ctx, incomplete, completions_out):239 # Add subcommand completions.240 if isinstance(ctx.command, MultiCommand):241 completions_out.extend(227- [(c.name, c.get_short_help_str()) for c in get_visible_commands_starting_with(ctx, incomplete)])242+ [243+ (c.name, c.get_short_help_str())244+ for c in get_visible_commands_starting_with(ctx, incomplete)245+ ]246+ )247 248 # Walk up the context list and add any other completion possibilities from chained commands249 while ctx.parent is not None:250 ctx = ctx.parent251 if isinstance(ctx.command, MultiCommand) and ctx.command.chain:233- remaining_commands = [c for c in get_visible_commands_starting_with(ctx, incomplete)234- if c.name not in ctx.protected_args]235- completions_out.extend([(c.name, c.get_short_help_str()) for c in remaining_commands])252+ remaining_commands = [253+ c254+ for c in get_visible_commands_starting_with(ctx, incomplete)255+ if c.name not in ctx.protected_args256+ ]257+ completions_out.extend(258+ [(c.name, c.get_short_help_str()) for c in remaining_commands]259+ )260 261 262 def get_choices(cli, prog_name, args, incomplete):263 """17 unmodified lines281 partition_incomplete = incomplete.partition(WORDBREAK)282 all_args.append(partition_incomplete[0])283 incomplete = partition_incomplete[2]284 elif incomplete == WORDBREAK:261- incomplete = ''285+ incomplete = ""286 287 completions = []288 if not has_double_dash and start_of_option(incomplete):289 # completions for partial options290 for param in ctx.command.params:291 if isinstance(param, Option) and not param.hidden:268- param_opts = [param_opt for param_opt in param.opts +269- param.secondary_opts if param_opt not in all_args or param.multiple]270- completions.extend([(o, param.help) for o in param_opts if o.startswith(incomplete)])292+ param_opts = [293+ param_opt294+ for param_opt in param.opts + param.secondary_opts295+ if param_opt not in all_args or param.multiple296+ ]297+ completions.extend(298+ [(o, param.help) for o in param_opts if o.startswith(incomplete)]299+ )300 return completions301 # completion for option values from user supplied values302 for param in ctx.command.params:303 if is_incomplete_option(all_args, param):8 unmodified lines312 return sorted(completions)313 314 315 def do_complete(cli, prog_name, include_descriptions):287- cwords = split_arg_string(os.environ['COMP_WORDS'])288- cword = int(os.environ['COMP_CWORD'])316+ cwords = split_arg_string(os.environ["COMP_WORDS"])317+ cword = int(os.environ["COMP_CWORD"])318 args = cwords[1:cword]319 try:320 incomplete = cwords[cword]321 except IndexError:293- incomplete = ''322+ incomplete = ""323 324 for item in get_choices(cli, prog_name, args, incomplete):325 echo(item[0])326 if include_descriptions:327 # ZSH has trouble dealing with empty array parameters when328 # returned from commands, use '_' to indicate no description329 # is present.301- echo(item[1] if item[1] else '_')330+ echo(item[1] if item[1] else "_")331 332 return True333 334 31 unmodified linesmodified:src/click/_compat.py+121 added-103 removed
4 unmodified lines5 import sys6 from weakref import WeakKeyDictionary7 8 PY2 = sys.version_info[0] == 29-CYGWIN = sys.platform.startswith('cygwin')10-MSYS2 = sys.platform.startswith('win') and ('GCC' in sys.version)9+CYGWIN = sys.platform.startswith("cygwin")10+MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)11 # Determine local App Engine environment, per Google's own suggestion12-APP_ENGINE = ('APPENGINE_RUNTIME' in os.environ and13- 'Development/' in os.environ.get('SERVER_SOFTWARE', ''))14-WIN = sys.platform.startswith('win') and not APP_ENGINE and not MSYS212+APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(13+ "SERVER_SOFTWARE", ""14+)15+WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS216 DEFAULT_COLUMNS = 8017 18 19 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")2 unmodified lines22 def get_filesystem_encoding():23 return sys.getfilesystemencoding() or sys.getdefaultencoding()24 25 25-def _make_text_stream(stream, encoding, errors,26- force_readable=False, force_writable=False):26+def _make_text_stream(27+ stream, encoding, errors, force_readable=False, force_writable=False28+):29 if encoding is None:30 encoding = get_best_encoding(stream)31 if errors is None:30- errors = 'replace'31- return _NonClosingTextIOWrapper(stream, encoding, errors,32- line_buffering=True,33- force_readable=force_readable,34- force_writable=force_writable)32+ errors = "replace"33+ return _NonClosingTextIOWrapper(34+ stream,35+ encoding,36+ errors,37+ line_buffering=True,38+ force_readable=force_readable,39+ force_writable=force_writable,40+ )41 42 43 def is_ascii_encoding(encoding):44 """Checks if a given encoding is ascii."""45 try:40- return codecs.lookup(encoding).name == 'ascii'46+ return codecs.lookup(encoding).name == "ascii"47 except LookupError:48 return False49 50 51 def get_best_encoding(stream):52 """Returns the default stream encoding if not found."""47- rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()53+ rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()54 if is_ascii_encoding(rv):49- return 'utf-8'55+ return "utf-8"56 return rv57 58 59 class _NonClosingTextIOWrapper(io.TextIOWrapper):54-55- def __init__(self, stream, encoding, errors,56- force_readable=False, force_writable=False, **extra):57- self._stream = stream = _FixupStream(stream, force_readable,58- force_writable)60+ def __init__(61+ self,62+ stream,63+ encoding,64+ errors,65+ force_readable=False,66+ force_writable=False,67+ **extra68+ ):69+ self._stream = stream = _FixupStream(stream, force_readable, force_writable)70 io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)71 72 # The io module is a place where the Python 3 text behavior73 # was forced upon Python 2, so we need to unbreak74 # it to look like Python 2.75 if PY2:76+77 def write(self, x):78 if isinstance(x, str) or is_bytes(x):79 try:80 self.flush()35 unmodified lines116 def __getattr__(self, name):117 return getattr(self._stream, name)118 119 def read1(self, size):108- f = getattr(self._stream, 'read1', None)120+ f = getattr(self._stream, "read1", None)121 if f is not None:122 return f(size)123 # We only dispatch to readline instead of read in Python 2 as we124 # do not want cause problems with the different implementation4 unmodified lines129 130 def readable(self):131 if self._force_readable:132 return True121- x = getattr(self._stream, 'readable', None)133+ x = getattr(self._stream, "readable", None)134 if x is not None:135 return x()136 try:137 self._stream.read(0)3 unmodified lines141 142 def writable(self):143 if self._force_writable:144 return True133- x = getattr(self._stream, 'writable', None)145+ x = getattr(self._stream, "writable", None)146 if x is not None:147 return x()148 try:137- self._stream.write('')149+ self._stream.write("")150 except Exception:151 try:140- self._stream.write(b'')152+ self._stream.write(b"")153 except Exception:154 return False155 return True156 157 def seekable(self):146- x = getattr(self._stream, 'seekable', None)158+ x = getattr(self._stream, "seekable", None)159 if x is not None:160 return x()161 try:162 self._stream.seek(self._stream.tell())14 unmodified lines177 178 def is_bytes(x):179 return isinstance(x, (buffer, bytearray))180 169- _identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')181+ _identifier_re = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")182 183 # For Windows, we need to force stdout/stdin/stderr to binary if it's184 # fetched for that. This obviously is not the most correct way to do185 # it as it changes global state. Unfortunately, there does not seem to19 unmodified lines205 import msvcrt206 except ImportError:207 pass208 else:209+210 def set_binary_mode(f):211 try:212 fileno = f.fileno()213 except Exception:6 unmodified lines220 import fcntl221 except ImportError:222 pass223 else:224+225 def set_binary_mode(f):226 try:227 fileno = f.fileno()228 except Exception:9 unmodified lines238 def get_binary_stdin():239 return set_binary_mode(sys.stdin)240 241 def get_binary_stdout():228- _wrap_std_stream('stdout')242+ _wrap_std_stream("stdout")243 return set_binary_mode(sys.stdout)244 245 def get_binary_stderr():232- _wrap_std_stream('stderr')246+ _wrap_std_stream("stderr")247 return set_binary_mode(sys.stderr)248 249 def get_text_stdin(encoding=None, errors=None):250 rv = _get_windows_console_stream(sys.stdin, encoding, errors)251 if rv is not None:252 return rv239- return _make_text_stream(sys.stdin, encoding, errors,240- force_readable=True)253+ return _make_text_stream(sys.stdin, encoding, errors, force_readable=True)254 255 def get_text_stdout(encoding=None, errors=None):243- _wrap_std_stream('stdout')256+ _wrap_std_stream("stdout")257 rv = _get_windows_console_stream(sys.stdout, encoding, errors)258 if rv is not None:259 return rv247- return _make_text_stream(sys.stdout, encoding, errors,248- force_writable=True)260+ return _make_text_stream(sys.stdout, encoding, errors, force_writable=True)261 262 def get_text_stderr(encoding=None, errors=None):251- _wrap_std_stream('stderr')263+ _wrap_std_stream("stderr")264 rv = _get_windows_console_stream(sys.stderr, encoding, errors)265 if rv is not None:266 return rv255- return _make_text_stream(sys.stderr, encoding, errors,256- force_writable=True)267+ return _make_text_stream(sys.stderr, encoding, errors, force_writable=True)268 269 def filename_to_ui(value):270 if isinstance(value, bytes):260- value = value.decode(get_filesystem_encoding(), 'replace')271+ value = value.decode(get_filesystem_encoding(), "replace")272 return value273+274+275 else:276 import io277+278 text_type = str279 raw_input = input280 string_types = (str,)281 int_types = (int,)15 unmodified lines297 # closed. In this case, we assume the default.298 299 def _is_binary_writer(stream, default=False):300 try:287- stream.write(b'')301+ stream.write(b"")302 except Exception:303 try:290- stream.write('')304+ stream.write("")305 return False306 except Exception:307 pass308 return default6 unmodified lines315 # we need to deal with this case explicitly.316 if _is_binary_reader(stream, False):317 return stream318 305- buf = getattr(stream, 'buffer', None)319+ buf = getattr(stream, "buffer", None)320 321 # Same situation here; this time we assume that the buffer is322 # actually binary in case it's closed.323 if buf is not None and _is_binary_reader(buf, True):6 unmodified lines330 # we need to deal with this case explicitly.331 if _is_binary_writer(stream, False):332 return stream333 320- buf = getattr(stream, 'buffer', None)334+ buf = getattr(stream, "buffer", None)335 336 # Same situation here; this time we assume that the buffer is337 # actually binary in case it's closed.338 if buf is not None and _is_binary_writer(buf, True):4 unmodified lines343 # If the stream does not have an encoding set, we assume it's set344 # to ASCII. This appears to happen in certain unittest345 # environments. It's not quite clear what the correct behavior is346 # but this at least will force Click to recover somehow.333- return is_ascii_encoding(getattr(stream, 'encoding', None) or 'ascii')347+ return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")348 349 def _is_compat_stream_attr(stream, attr, value):350 """A stream attribute is compatible if it is equal to the351 desired value or the desired value is unset and the attribute5 unmodified lines357 def _is_compatible_text_stream(stream, encoding, errors):358 """Check if a stream's encoding and errors attributes are359 compatible with the desired values.360 """347- return (348- _is_compat_stream_attr(stream, "encoding", encoding)349- and _is_compat_stream_attr(stream, "errors", errors)350- )361+ return _is_compat_stream_attr(362+ stream, "encoding", encoding363+ ) and _is_compat_stream_attr(stream, "errors", errors)364 365 def _force_correct_text_stream(366 text_stream,367 encoding,7 unmodified lines375 binary_reader = text_stream376 else:377 # If the stream looks compatible, and won't default to a378 # misconfigured ascii encoding, return it as-is.366- if (367- _is_compatible_text_stream(text_stream, encoding, errors)368- and not (369- encoding is None370- and _stream_is_misconfigured(text_stream)371- )379+ if _is_compatible_text_stream(text_stream, encoding, errors) and not (380+ encoding is None and _stream_is_misconfigured(text_stream)381 ):382 return text_stream383 384 # Otherwise, get the underlying binary reader.41 unmodified lines426 427 def get_binary_stdin():428 reader = _find_binary_reader(sys.stdin)429 if reader is None:421- raise RuntimeError('Was not able to determine binary '422- 'stream for sys.stdin.')430+ raise RuntimeError(431+ "Was not able to determine binary stream for sys.stdin."432+ )433 return reader434 435 def get_binary_stdout():436 writer = _find_binary_writer(sys.stdout)437 if writer is None:428- raise RuntimeError('Was not able to determine binary '429- 'stream for sys.stdout.')438+ raise RuntimeError(439+ "Was not able to determine binary stream for sys.stdout."440+ )441 return writer442 443 def get_binary_stderr():444 writer = _find_binary_writer(sys.stderr)445 if writer is None:435- raise RuntimeError('Was not able to determine binary '436- 'stream for sys.stderr.')446+ raise RuntimeError(447+ "Was not able to determine binary stream for sys.stderr."448+ )449 return writer450 451 def get_text_stdin(encoding=None, errors=None):452 rv = _get_windows_console_stream(sys.stdin, encoding, errors)453 if rv is not None:454 return rv443- return _force_correct_text_reader(sys.stdin, encoding, errors,444- force_readable=True)455+ return _force_correct_text_reader(456+ sys.stdin, encoding, errors, force_readable=True457+ )458 459 def get_text_stdout(encoding=None, errors=None):460 rv = _get_windows_console_stream(sys.stdout, encoding, errors)461 if rv is not None:462 return rv450- return _force_correct_text_writer(sys.stdout, encoding, errors,451- force_writable=True)463+ return _force_correct_text_writer(464+ sys.stdout, encoding, errors, force_writable=True465+ )466 467 def get_text_stderr(encoding=None, errors=None):468 rv = _get_windows_console_stream(sys.stderr, encoding, errors)469 if rv is not None:470 return rv457- return _force_correct_text_writer(sys.stderr, encoding, errors,458- force_writable=True)471+ return _force_correct_text_writer(472+ sys.stderr, encoding, errors, force_writable=True473+ )474 475 def filename_to_ui(value):476 if isinstance(value, bytes):462- value = value.decode(get_filesystem_encoding(), 'replace')477+ value = value.decode(get_filesystem_encoding(), "replace")478 else:464- value = value.encode('utf-8', 'surrogateescape') \465- .decode('utf-8', 'replace')479+ value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")480 return value481 482 483 def get_streerror(e, default=None):470- if hasattr(e, 'strerror'):484+ if hasattr(e, "strerror"):485 msg = e.strerror486 else:487 if default is not None:488 msg = default489 else:490 msg = str(e)491 if isinstance(msg, bytes):478- msg = msg.decode('utf-8', 'replace')492+ msg = msg.decode("utf-8", "replace")493 return msg494 495 496 def _wrap_io_open(file, mode, encoding, errors):17 unmodified lines514 f = io.open(file, "b" + mode.replace("t", ""))515 return _make_text_stream(f, **kwargs)516 517 504-def open_stream(filename, mode='r', encoding=None, errors='strict', atomic=False):518+def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):519 binary = "b" in mode520 521 # Standard streams first. These are simple because they don't need522 # special handling for the atomic flag. It's entirely ignored.509- if filename == '-':510- if any(m in mode for m in ['w', 'a', 'x']):523+ if filename == "-":524+ if any(m in mode for m in ["w", "a", "x"]):525 if binary:526 return get_binary_stdout(), False527 return get_text_stdout(encoding=encoding, errors=errors), False528 if binary:4 unmodified lines533 if not atomic:534 return _wrap_io_open(filename, mode, encoding, errors), True535 536 # Some usability stuff for atomic writes523- if 'a' in mode:537+ if "a" in mode:538 raise ValueError(525- 'Appending to an existing file is not supported, because that '526- 'would involve an expensive `copy`-operation to a temporary '527- 'file. Open the file in normal `w`-mode and copy explicitly '528- 'if that\'s what you\'re after.'539+ "Appending to an existing file is not supported, because that "540+ "would involve an expensive `copy`-operation to a temporary "541+ "file. Open the file in normal `w`-mode and copy explicitly "542+ "if that's what you're after."543 )530- if 'x' in mode:531- raise ValueError('Use the `overwrite`-parameter instead.')532- if 'w' not in mode:533- raise ValueError('Atomic writes only make sense with `w`-mode.')544+ if "x" in mode:545+ raise ValueError("Use the `overwrite`-parameter instead.")546+ if "w" not in mode:547+ raise ValueError("Atomic writes only make sense with `w`-mode.")548 549 # Atomic writes are more complicated. They work by opening a file550 # as a proxy in the same folder and then using the fdopen551 # functionality to wrap it in a Python file. Then we wrap it in an8 unmodified lines560 561 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL562 563 if binary:550- flags |= getattr(os, 'O_BINARY', 0)564+ flags |= getattr(os, "O_BINARY", 0)565 566 while True:567 tmp_filename = os.path.join(568 os.path.dirname(filename),555- '.__atomic-write%08x' % (random.randrange(1 << 32),),569+ ".__atomic-write%08x" % (random.randrange(1 << 32),),570 )571 try:572 fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)573 break14 unmodified lines588 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True589 590 591 # Used in a destructor call, needs extra protection from interpreter cleanup.578-if hasattr(os, 'replace'):592+if hasattr(os, "replace"):593 _replace = os.replace594 _can_replace = True595 else:596 _replace = os.rename597 _can_replace = not WIN598 599 600 class _AtomicFile(object):587-601 def __init__(self, f, tmp_filename, real_filename):602 self._f = f603 self._tmp_filename = tmp_filename604 self._real_filename = real_filename33 unmodified lines638 get_winterm_size = None639 640 641 def strip_ansi(value):629- return _ansi_re.sub('', value)642+ return _ansi_re.sub("", value)643 644 645 def _is_jupyter_kernel_output(stream):646 if WIN:25 unmodified lines672 from ._winconsole import _get_windows_console_stream, _wrap_std_stream673 674 def _get_argv_encoding():675 import locale676+677 return locale.getpreferredencoding()678 679 if PY2:680+666- def raw_input(prompt=''):681+ def raw_input(prompt=""):682 sys.stderr.flush()683 if prompt:684 stdout = _default_text_stdout()685 stdout.write(prompt)686 stdin = _default_text_stdin()672- return stdin.readline().rstrip('\r\n')687+ return stdin.readline().rstrip("\r\n")688 689 try:690 import colorama691 except ImportError:33 unmodified lines725 return rv726 727 def get_winterm_size():728 win = colorama.win32.GetConsoleScreenBufferInfo(714- colorama.win32.STDOUT).srWindow729+ colorama.win32.STDOUT730+ ).srWindow731 return win.Right - win.Left, win.Bottom - win.Top732+733+734 else:735+736 def _get_argv_encoding():718- return getattr(sys.stdin, 'encoding', None) or get_filesystem_encoding()737+ return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()738 739 _get_windows_console_stream = lambda *x: None740 _wrap_std_stream = lambda *x: None741 10 unmodified lines752 753 754 def _make_cached_stream_func(src_func, wrapper_func):755 cache = WeakKeyDictionary()756+757 def func():758 stream = src_func()759 try:760 rv = cache.get(stream)7 unmodified lines768 cache[stream] = rv769 except Exception:770 pass771 return rv772+773 return func774 775 755-_default_text_stdin = _make_cached_stream_func(756- lambda: sys.stdin, get_text_stdin)757-_default_text_stdout = _make_cached_stream_func(758- lambda: sys.stdout, get_text_stdout)759-_default_text_stderr = _make_cached_stream_func(760- lambda: sys.stderr, get_text_stderr)776+_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)777+_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)778+_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)779 780 781 binary_streams = {764- 'stdin': get_binary_stdin,765- 'stdout': get_binary_stdout,766- 'stderr': get_binary_stderr,782+ "stdin": get_binary_stdin,783+ "stdout": get_binary_stdout,784+ "stderr": get_binary_stderr,785 }786 787 text_streams = {770- 'stdin': get_text_stdin,771- 'stdout': get_text_stdout,772- 'stderr': get_text_stderr,788+ "stdin": get_text_stdin,789+ "stdout": get_text_stdout,790+ "stderr": get_text_stderr,791 }modified:src/click/_termui_impl.py+108 added-88 removed
22 unmodified lines23 from ._compat import WIN24 from .exceptions import ClickException25 from .utils import echo26 27-if os.name == 'nt':28- BEFORE_BAR = '\r'29- AFTER_BAR = '\n'27+if os.name == "nt":28+ BEFORE_BAR = "\r"29+ AFTER_BAR = "\n"30 else:31- BEFORE_BAR = '\r\033[?25l'32- AFTER_BAR = '\033[?25h\n'31+ BEFORE_BAR = "\r\033[?25l"32+ AFTER_BAR = "\033[?25h\n"33 34 35 def _length_hint(obj):36 """Returns the length hint of an object."""7 unmodified lines44 try:45 hint = get_hint(obj)46 except TypeError:47 return None48- if hint is NotImplemented or \49- not isinstance(hint, int_types) or \50- hint < 0:48+ if hint is NotImplemented or not isinstance(hint, int_types) or hint < 0:49 return None50 return hint51 52 53 class ProgressBar(object):56-57- def __init__(self, iterable, length=None, fill_char='#', empty_char=' ',58- bar_template='%(bar)s', info_sep=' ', show_eta=True,59- show_percent=None, show_pos=False, item_show_func=None,60- label=None, file=None, color=None, width=30):54+ def __init__(55+ self,56+ iterable,57+ length=None,58+ fill_char="#",59+ empty_char=" ",60+ bar_template="%(bar)s",61+ info_sep=" ",62+ show_eta=True,63+ show_percent=None,64+ show_pos=False,65+ item_show_func=None,66+ label=None,67+ file=None,68+ color=None,69+ width=30,70+ ):71 self.fill_char = fill_char72 self.empty_char = empty_char73 self.bar_template = bar_template74 self.info_sep = info_sep75 self.show_eta = show_eta76 self.show_percent = show_percent77 self.show_pos = show_pos78 self.item_show_func = item_show_func69- self.label = label or ''79+ self.label = label or ""80 if file is None:81 file = _default_text_stdout()82 self.file = file83 self.color = color3 unmodified lines87 if length is None:88 length = _length_hint(iterable)89 if iterable is None:90 if length is None:81- raise TypeError('iterable or length is required')91+ raise TypeError("iterable or length is required")92 iterable = range_type(length)93 self.iter = iter(iterable)94 self.length = length95 self.length_known = length is not None18 unmodified lines114 self.render_finish()115 116 def __iter__(self):117 if not self.entered:108- raise RuntimeError('You need to use progress bars in a with block.')118+ raise RuntimeError("You need to use progress bars in a with block.")119 self.render_progress()120 return self.generator()121 122 def __next__(self):44 unmodified lines167 hours = t % 24168 t //= 24169 if t > 0:170 days = t161- return '%dd %02d:%02d:%02d' % (days, hours, minutes, seconds)171+ return "%dd %02d:%02d:%02d" % (days, hours, minutes, seconds)172 else:163- return '%02d:%02d:%02d' % (hours, minutes, seconds)164- return ''173+ return "%02d:%02d:%02d" % (hours, minutes, seconds)174+ return ""175 176 def format_pos(self):177 pos = str(self.pos)178 if self.length_known:169- pos += '/%s' % self.length179+ pos += "/%s" % self.length180 return pos181 182 def format_pct(self):173- return ('% 4d%%' % int(self.pct * 100))[1:]183+ return ("% 4d%%" % int(self.pct * 100))[1:]184 185 def format_bar(self):186 if self.length_known:187 bar_length = int(self.pct * self.width)3 unmodified lines191 bar = self.fill_char * self.width192 else:193 bar = list(self.empty_char * (self.width or 1))194 if self.time_per_iteration != 0:185- bar[int((math.cos(self.pos * self.time_per_iteration)186- / 2.0 + 0.5) * self.width)] = self.fill_char187- bar = ''.join(bar)195+ bar[196+ int(197+ (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)198+ * self.width199+ )200+ ] = self.fill_char201+ bar = "".join(bar)202 return bar203 204 def format_progress_line(self):205 show_percent = self.show_percent12 unmodified lines218 item_info = self.item_show_func(self.current_item)219 if item_info is not None:220 info_bits.append(item_info)221 208- return (self.bar_template % {209- 'label': self.label,210- 'bar': self.format_bar(),211- 'info': self.info_sep.join(info_bits)212- }).rstrip()222+ return (223+ self.bar_template224+ % {225+ "label": self.label,226+ "bar": self.format_bar(),227+ "info": self.info_sep.join(info_bits),228+ }229+ ).rstrip()230 231 def render_progress(self):232 from .termui import get_terminal_size233 8 unmodified lines242 clutter_length = term_len(self.format_progress_line())243 new_width = max(0, get_terminal_size()[0] - clutter_length)244 if new_width < old_width:245 buf.append(BEFORE_BAR)229- buf.append(' ' * self.max_width)246+ buf.append(" " * self.max_width)247 self.max_width = new_width248 self.width = new_width249 250 clear_width = self.width6 unmodified lines257 if self.max_width is None or self.max_width < line_len:258 self.max_width = line_len259 260 buf.append(line)244- buf.append(' ' * (clear_width - line_len))245- line = ''.join(buf)261+ buf.append(" " * (clear_width - line_len))262+ line = "".join(buf)263 # Render the line only if it changed.264 265 if line != self._last_line and not self.is_fast():266 self._last_line = line43 unmodified lines310 # `iter(bar)` and `next(bar)`. `next()` in particular may call311 # `self.generator()` repeatedly, and this must remain safe in312 # order for that interface to work.313 if not self.entered:297- raise RuntimeError('You need to use progress bars in a with block.')314+ raise RuntimeError("You need to use progress bars in a with block.")315 316 if self.is_hidden:317 for rv in self.iter:318 yield rv10 unmodified lines329 """Decide what method to use for paging through text."""330 stdout = _default_text_stdout()331 if not isatty(sys.stdin) or not isatty(stdout):332 return _nullpager(stdout, generator, color)316- pager_cmd = (os.environ.get('PAGER', None) or '').strip()333+ pager_cmd = (os.environ.get("PAGER", None) or "").strip()334 if pager_cmd:335 if WIN:336 return _tempfilepager(generator, pager_cmd, color)337 return _pipepager(generator, pager_cmd, color)321- if os.environ.get('TERM') in ('dumb', 'emacs'):338+ if os.environ.get("TERM") in ("dumb", "emacs"):339 return _nullpager(stdout, generator, color)323- if WIN or sys.platform.startswith('os2'):324- return _tempfilepager(generator, 'more <', color)325- if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:326- return _pipepager(generator, 'less', color)340+ if WIN or sys.platform.startswith("os2"):341+ return _tempfilepager(generator, "more <", color)342+ if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:343+ return _pipepager(generator, "less", color)344 345 import tempfile346+347 fd, filename = tempfile.mkstemp()348 os.close(fd)349 try:332- if hasattr(os, 'system') and os.system("more %s" % shlex_quote(filename)) == 0:333- return _pipepager(generator, 'more', color)350+ if hasattr(os, "system") and os.system("more %s" % shlex_quote(filename)) == 0:351+ return _pipepager(generator, "more", color)352 return _nullpager(stdout, generator, color)353 finally:354 os.unlink(filename)355 2 unmodified lines358 """Page through text by feeding it to another program. Invoking a359 pager through this might support colors.360 """361 import subprocess362+363 env = dict(os.environ)364 365 # If we're piping to less we might support colors under the366 # condition that348- cmd_detail = cmd.rsplit('/', 1)[-1].split()349- if color is None and cmd_detail[0] == 'less':350- less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:])367+ cmd_detail = cmd.rsplit("/", 1)[-1].split()368+ if color is None and cmd_detail[0] == "less":369+ less_flags = os.environ.get("LESS", "") + " ".join(cmd_detail[1:])370 if not less_flags:352- env['LESS'] = '-R'371+ env["LESS"] = "-R"372 color = True354- elif 'r' in less_flags or 'R' in less_flags:373+ elif "r" in less_flags or "R" in less_flags:374 color = True375 357- c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,358- env=env)376+ c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)377 encoding = get_best_encoding(c.stdin)378 try:379 for text in generator:380 if not color:381 text = strip_ansi(text)382 365- c.stdin.write(text.encode(encoding, 'replace'))383+ c.stdin.write(text.encode(encoding, "replace"))384 except (IOError, KeyboardInterrupt):385 pass386 else:387 c.stdin.close()17 unmodified lines405 406 def _tempfilepager(generator, cmd, color):407 """Page through text by invoking a program on a temporary file."""408 import tempfile409+410 filename = tempfile.mktemp()411 # TODO: This never terminates if the passed generator never terminates.412 text = "".join(generator)413 if not color:414 text = strip_ansi(text)415 encoding = get_best_encoding(sys.stdout)397- with open_stream(filename, 'wb')[0] as f:416+ with open_stream(filename, "wb")[0] as f:417 f.write(text.encode(encoding))418 try:419 os.system("%s %s" % (shlex_quote(cmd), shlex_quote(filename)))420 finally:8 unmodified lines429 stream.write(text)430 431 432 class Editor(object):414-415- def __init__(self, editor=None, env=None, require_save=True,433+ def __init__(self, editor=None, env=None, require_save=True, extension=".txt"):416- extension='.txt'):434 self.editor = editor435 self.env = env436 self.require_save = require_save437 self.extension = extension438 439 def get_editor(self):440 if self.editor is not None:441 return self.editor425- for key in 'VISUAL', 'EDITOR':442+ for key in "VISUAL", "EDITOR":443 rv = os.environ.get(key)444 if rv:445 return rv446 if WIN:430- return 'notepad'431- for editor in 'sensible-editor', 'vim', 'nano':432- if os.system('which %s >/dev/null 2>&1' % editor) == 0:447+ return "notepad"448+ for editor in "sensible-editor", "vim", "nano":449+ if os.system("which %s >/dev/null 2>&1" % editor) == 0:450 return editor434- return 'vi'451+ return "vi"452 453 def edit_file(self, filename):454 import subprocess455+456 editor = self.get_editor()457 if self.env:458 environ = os.environ.copy()459 environ.update(self.env)2 unmodified lines462 try:463 c = subprocess.Popen(464 "%s %s" % (shlex_quote(editor), shlex_quote(filename)),465 env=environ,448- shell=True466+ shell=True,467 )468 exit_code = c.wait()469 if exit_code != 0:452- raise ClickException('%s: Editing failed!' % editor)470+ raise ClickException("%s: Editing failed!" % editor)471 except OSError as e:454- raise ClickException('%s: Editing failed: %s' % (editor, e))472+ raise ClickException("%s: Editing failed: %s" % (editor, e))473 474 def edit(self, text):475 import tempfile476 459- text = text or ''460- if text and not text.endswith('\n'):461- text += '\n'477+ text = text or ""478+ if text and not text.endswith("\n"):479+ text += "\n"480 463- fd, name = tempfile.mkstemp(prefix='editor-', suffix=self.extension)481+ fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)482 try:483 if WIN:466- encoding = 'utf-8-sig'467- text = text.replace('\n', '\r\n')484+ encoding = "utf-8-sig"485+ text = text.replace("\n", "\r\n")486 else:469- encoding = 'utf-8'487+ encoding = "utf-8"488 text = text.encode(encoding)489 472- f = os.fdopen(fd, 'wb')490+ f = os.fdopen(fd, "wb")491 f.write(text)492 f.close()493 timestamp = os.path.getmtime(name)494 495 self.edit_file(name)496 479- if self.require_save \480- and os.path.getmtime(name) == timestamp:497+ if self.require_save and os.path.getmtime(name) == timestamp:498 return None499 483- f = open(name, 'rb')500+ f = open(name, "rb")501 try:502 rv = f.read()503 finally:504 f.close()488- return rv.decode('utf-8-sig').replace('\r\n', '\n')505+ return rv.decode("utf-8-sig").replace("\r\n", "\n")506 finally:507 os.unlink(name)508 509 4 unmodified lines514 try:515 import urllib516 except ImportError:517 import urllib501- if url.startswith('file://'):518+ if url.startswith("file://"):519 url = urllib.unquote(url[7:])520 return url521 505- if sys.platform == 'darwin':506- args = ['open']522+ if sys.platform == "darwin":523+ args = ["open"]524 if wait:508- args.append('-W')525+ args.append("-W")526 if locate:510- args.append('-R')527+ args.append("-R")528 args.append(_unquote_file(url))512- null = open('/dev/null', 'w')529+ null = open("/dev/null", "w")530 try:531 return subprocess.Popen(args, stderr=null).wait()532 finally:533 null.close()13 unmodified lines547 return os.system(args)548 549 try:550 if locate:534- url = os.path.dirname(_unquote_file(url)) or '.'551+ url = os.path.dirname(_unquote_file(url)) or "."552 else:553 url = _unquote_file(url)537- c = subprocess.Popen(['xdg-open', url])554+ c = subprocess.Popen(["xdg-open", url])555 if wait:556 return c.wait()557 return 0558 except OSError:542- if url.startswith(('http://', 'https://')) and not locate and not wait:559+ if url.startswith(("http://", "https://")) and not locate and not wait:560 import webbrowser561+562 webbrowser.open(url)563 return 0564 return 1565 566 567 def _translate_ch_to_exc(ch):550- if ch == u'\x03':568+ if ch == u"\x03":569 raise KeyboardInterrupt()552- if ch == u'\x04' and not WIN: # Unix-like, Ctrl+D570+ if ch == u"\x04" and not WIN: # Unix-like, Ctrl+D571 raise EOFError()554- if ch == u'\x1a' and WIN: # Windows, Ctrl+Z572+ if ch == u"\x1a" and WIN: # Windows, Ctrl+Z573 raise EOFError()574 575 576 if WIN:38 unmodified lines615 else:616 func = msvcrt.getwch617 618 rv = func()601- if rv in (u'\x00', u'\xe0'):619+ if rv in (u"\x00", u"\xe0"):620 # \x00 and \xe0 are control characters that indicate special key,621 # see above.622 rv += func()623 _translate_ch_to_exc(rv)624 return rv625+626+627 else:628 import tty629 import termios630 631 @contextlib.contextmanager632 def raw_terminal():633 if not isatty(sys.stdin):614- f = open('/dev/tty')634+ f = open("/dev/tty")635 fd = f.fileno()636 else:637 fd = sys.stdin.fileno()638 f = None12 unmodified lines651 652 def getchar(echo):653 with raw_terminal() as fd:654 ch = os.read(fd, 32)635- ch = ch.decode(get_best_encoding(sys.stdin), 'replace')655+ ch = ch.decode(get_best_encoding(sys.stdin), "replace")656 if echo and isatty(sys.stdout):657 sys.stdout.write(ch)658 _translate_ch_to_exc(ch)659 return chmodified:src/click/_textwrap.py+1 added-2 removed
1 unmodified line2 from contextlib import contextmanager3 4 5 class TextWrapper(textwrap.TextWrapper):6-6 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):7 space_left = max(width - cur_len, 1)8 9 if self.break_long_words:23 unmodified lines33 indent = self.initial_indent34 if idx > 0:35 indent = self.subsequent_indent36 rv.append(indent + line)38- return '\n'.join(rv)37+ return "\n".join(rv)modified:src/click/_unicodefun.py+51 added-42 removed
6 unmodified lines7 # If someone wants to vendor click, we want to ensure the8 # correct package is discovered. Ideally we could use a9 # relative import here but unfortunately Python does not10 # support that.11-click = sys.modules[__name__.rsplit('.', 1)[0]]11+click = sys.modules[__name__.rsplit(".", 1)[0]]12 13 14 def _find_unicode_literals_frame():15 import __future__16+16- if not hasattr(sys, '_getframe'): # not all Python implementations have it17+ if not hasattr(sys, "_getframe"): # not all Python implementations have it18 return 019 frm = sys._getframe(1)20 idx = 121 while frm is not None:21- if frm.f_globals.get('__name__', '').startswith('click.'):22+ if frm.f_globals.get("__name__", "").startswith("click."):23 frm = frm.f_back24 idx += 125 elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:26 return idx10 unmodified lines37 bad_frame = _find_unicode_literals_frame()38 if bad_frame <= 0:39 return40 from warnings import warn40- warn(Warning('Click detected the use of the unicode_literals '41- '__future__ import. This is heavily discouraged '42- 'because it can introduce subtle bugs in your '43- 'code. You should instead use explicit u"" literals '44- 'for your unicode strings. For more information see '45- 'https://click.palletsprojects.com/en/7.x/python3/'),46- stacklevel=bad_frame)41 42+ warn(43+ Warning(44+ "Click detected the use of the unicode_literals "45+ "__future__ import. This is heavily discouraged "46+ "because it can introduce subtle bugs in your "47+ 'code. You should instead use explicit u"" literals '48+ "for your unicode strings. For more information see "49+ "https://click.palletsprojects.com/en/7.x/python3/"50+ ),51+ stacklevel=bad_frame,52+ )53 54+55 def _verify_python3_env():56 """Ensures that the environment is good for unicode on Python 3."""57 if PY2:58 return59 try:60 import locale61+62 fs_enc = codecs.lookup(locale.getpreferredencoding()).name63 except Exception:57- fs_enc = 'ascii'58- if fs_enc != 'ascii':64+ fs_enc = "ascii"65+ if fs_enc != "ascii":66 return67 61- extra = ''62- if os.name == 'posix':68+ extra = ""69+ if os.name == "posix":70 import subprocess71+72 try:65- rv = subprocess.Popen(['locale', '-a'], stdout=subprocess.PIPE,66- stderr=subprocess.PIPE).communicate()[0]73+ rv = subprocess.Popen(74+ ["locale", "-a"], stdout=subprocess.PIPE, stderr=subprocess.PIPE75+ ).communicate()[0]76 except OSError:68- rv = b''77+ rv = b""78 good_locales = set()79 has_c_utf8 = False80 81 # Make sure we're operating on text here.82 if isinstance(rv, bytes):74- rv = rv.decode('ascii', 'replace')83+ rv = rv.decode("ascii", "replace")84 85 for line in rv.splitlines():86 locale = line.strip()78- if locale.lower().endswith(('.utf-8', '.utf8')):87+ if locale.lower().endswith((".utf-8", ".utf8")):88 good_locales.add(locale)80- if locale.lower() in ('c.utf8', 'c.utf-8'):89+ if locale.lower() in ("c.utf8", "c.utf-8"):90 has_c_utf8 = True91 83- extra += '\n\n'92+ extra += "\n\n"93 if not good_locales:94 extra += (86- 'Additional information: on this system no suitable UTF-8\n'87- 'locales were discovered. This most likely requires resolving\n'88- 'by reconfiguring the locale system.'95+ "Additional information: on this system no suitable UTF-8\n"96+ "locales were discovered. This most likely requires resolving\n"97+ "by reconfiguring the locale system."98 )99 elif has_c_utf8:100 extra += (92- 'This system supports the C.UTF-8 locale which is recommended.\n'93- 'You might be able to resolve your issue by exporting the\n'94- 'following environment variables:\n\n'95- ' export LC_ALL=C.UTF-8\n'96- ' export LANG=C.UTF-8'101+ "This system supports the C.UTF-8 locale which is recommended.\n"102+ "You might be able to resolve your issue by exporting the\n"103+ "following environment variables:\n\n"104+ " export LC_ALL=C.UTF-8\n"105+ " export LANG=C.UTF-8"106 )107 else:108 extra += (100- 'This system lists a couple of UTF-8 supporting locales that\n'101- 'you can pick from. The following suitable locales were\n'102- 'discovered: %s'103- ) % ', '.join(sorted(good_locales))109+ "This system lists a couple of UTF-8 supporting locales that\n"110+ "you can pick from. The following suitable locales were\n"111+ "discovered: %s"112+ ) % ", ".join(sorted(good_locales))113 114 bad_locale = None106- for locale in os.environ.get('LC_ALL'), os.environ.get('LANG'):107- if locale and locale.lower().endswith(('.utf-8', '.utf8')):115+ for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):116+ if locale and locale.lower().endswith((".utf-8", ".utf8")):117 bad_locale = locale118 if locale is not None:119 break120 if bad_locale is not None:121 extra += (113- '\n\nClick discovered that you exported a UTF-8 locale\n'114- 'but the locale system could not pick up from it because\n'122+ "\n\nClick discovered that you exported a UTF-8 locale\n"123+ "but the locale system could not pick up from it because\n"124 'it does not exist. The exported locale is "%s" but it\n'116- 'is not supported'125+ "is not supported"126 ) % bad_locale127 128 raise RuntimeError(120- 'Click will abort further execution because Python 3 was'121- ' configured to use ASCII as encoding for the environment.'122- ' Consult https://click.palletsprojects.com/en/7.x/python3/ for'123- ' mitigation steps.' + extra129+ "Click will abort further execution because Python 3 was"130+ " configured to use ASCII as encoding for the environment."131+ " Consult https://click.palletsprojects.com/en/7.x/python3/ for"132+ " mitigation steps." + extra133 )modified:src/click/_winconsole.py+76 added-54 removed
36 unmodified lines37 from ._compat import text_type38 39 try:40 from ctypes import pythonapi41+42 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer43 PyBuffer_Release = pythonapi.PyBuffer_Release44 except ImportError:45 pythonapi = None6 unmodified lines52 ReadConsoleW = kernel32.ReadConsoleW53 WriteConsoleW = kernel32.WriteConsoleW54 GetConsoleMode = kernel32.GetConsoleMode55 GetLastError = kernel32.GetLastError55-GetCommandLineW = WINFUNCTYPE(LPWSTR)(56- ('GetCommandLineW', windll.kernel32))57-CommandLineToArgvW = WINFUNCTYPE(58- POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(59- ('CommandLineToArgvW', windll.shell32))56+GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))57+CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(58+ ("CommandLineToArgvW", windll.shell32)59+)60 LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(61- ('LocalFree', windll.kernel32))61+ ("LocalFree", windll.kernel32)62+)63 64 65 STDIN_HANDLE = GetStdHandle(-10)66 STDOUT_HANDLE = GetStdHandle(-11)10 unmodified lines77 STDIN_FILENO = 078 STDOUT_FILENO = 179 STDERR_FILENO = 280 80-EOF = b'\x1a'81+EOF = b"\x1a"82 MAX_BYTES_WRITTEN = 3276783 84 85 class Py_buffer(ctypes.Structure):86 _fields_ = [86- ('buf', c_void_p),87- ('obj', py_object),88- ('len', c_ssize_t),89- ('itemsize', c_ssize_t),90- ('readonly', c_int),91- ('ndim', c_int),92- ('format', c_char_p),93- ('shape', c_ssize_p),94- ('strides', c_ssize_p),95- ('suboffsets', c_ssize_p),96- ('internal', c_void_p)87+ ("buf", c_void_p),88+ ("obj", py_object),89+ ("len", c_ssize_t),90+ ("itemsize", c_ssize_t),91+ ("readonly", c_int),92+ ("ndim", c_int),93+ ("format", c_char_p),94+ ("shape", c_ssize_p),95+ ("strides", c_ssize_p),96+ ("suboffsets", c_ssize_p),97+ ("internal", c_void_p),98 ]99 100 if PY2:100- _fields_.insert(-1, ('smalltable', c_ssize_t * 2))101+ _fields_.insert(-1, ("smalltable", c_ssize_t * 2))102 103 104 # On PyPy we cannot get buffers so our ability to operate here is105 # serverly limited.106 if pythonapi is None:107 get_buffer = None108 else:109+110 def get_buffer(obj, writable=False):111 buf = Py_buffer()112 flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE113 PyObject_GetBuffer(py_object(obj), byref(buf), flags)4 unmodified lines118 PyBuffer_Release(byref(buf))119 120 121 class _WindowsConsoleRawIOBase(io.RawIOBase):120-122 def __init__(self, handle):123 self.handle = handle124 125 def isatty(self):1 unmodified line127 return True128 129 130 class _WindowsConsoleReader(_WindowsConsoleRawIOBase):130-131 def readable(self):132 return True133 134 def readinto(self, b):135 bytes_to_be_read = len(b)136 if not bytes_to_be_read:137 return 0138 elif bytes_to_be_read % 2:139- raise ValueError('cannot read odd number of bytes from '140- 'UTF-16-LE encoded console')139+ raise ValueError(140+ "cannot read odd number of bytes from UTF-16-LE encoded console"141+ )142 143 buffer = get_buffer(b, writable=True)144 code_units_to_be_read = bytes_to_be_read // 2145 code_units_read = c_ulong()146 146- rv = ReadConsoleW(HANDLE(self.handle), buffer, code_units_to_be_read,147- byref(code_units_read), None)147+ rv = ReadConsoleW(148+ HANDLE(self.handle),149+ buffer,150+ code_units_to_be_read,151+ byref(code_units_read),152+ None,153+ )154 if GetLastError() == ERROR_OPERATION_ABORTED:155 # wait for KeyboardInterrupt156 time.sleep(0.1)157 if not rv:152- raise OSError('Windows error: %s' % GetLastError())158+ raise OSError("Windows error: %s" % GetLastError())159 160 if buffer[0] == EOF:161 return 0162 return 2 * code_units_read.value163 164 165 class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):160-166 def writable(self):167 return True168 169 @staticmethod170 def _get_error_message(errno):171 if errno == ERROR_SUCCESS:167- return 'ERROR_SUCCESS'172+ return "ERROR_SUCCESS"173 elif errno == ERROR_NOT_ENOUGH_MEMORY:169- return 'ERROR_NOT_ENOUGH_MEMORY'170- return 'Windows error %s' % errno174+ return "ERROR_NOT_ENOUGH_MEMORY"175+ return "Windows error %s" % errno176 177 def write(self, b):178 bytes_to_be_written = len(b)179 buf = get_buffer(b)175- code_units_to_be_written = min(bytes_to_be_written,176- MAX_BYTES_WRITTEN) // 2180+ code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2181 code_units_written = c_ulong()182 183+ WriteConsoleW(184+ HANDLE(self.handle),185+ buf,179- WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,180- byref(code_units_written), None)186+ code_units_to_be_written,187+ byref(code_units_written),188+ None,189+ )190 bytes_written = 2 * code_units_written.value191 192 if bytes_written == 0 and bytes_to_be_written > 0:193 raise OSError(self._get_error_message(GetLastError()))194 return bytes_written195 196 197 class ConsoleStream(object):189-198 def __init__(self, text_stream, byte_stream):199 self._text_stream = text_stream200 self.buffer = byte_stream201 20 unmodified lines222 def isatty(self):223 return self.buffer.isatty()224 225 def __repr__(self):218- return '<ConsoleStream name=%r encoding=%r>' % (219- self.name,220- self.encoding,221- )226+ return "<ConsoleStream name=%r encoding=%r>" % (self.name, self.encoding,)227 228 229 class WindowsChunkedWriter(object):230 """231 Wraps a stream (such as stdout), acting as a transparent proxy for all232 attribute access apart from method 'write()' which we wrap to write in233 limited chunks due to a Windows limitation on binary console streams.234 """235+236 def __init__(self, wrapped):237 # double-underscore everything to prevent clashes with names of238 # attributes on the wrapped stream object.239 self.__wrapped = wrapped6 unmodified lines246 written = 0247 248 while written < total_to_write:249 to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)244- self.__wrapped.write(text[written:written+to_write])250+ self.__wrapped.write(text[written : written + to_write])251 written += to_write252 253 254 _wrapped_std_streams = set()255 256 257 def _wrap_std_stream(name):258 # Python 2 & Windows 7 and below253- if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:259+ if (260+ PY2261+ and sys.getwindowsversion()[:2] <= (6, 1)262+ and name not in _wrapped_std_streams263+ ):264 setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))265 _wrapped_std_streams.add(name)266 267 268 def _get_text_stdin(buffer_stream):269 text_stream = _NonClosingTextIOWrapper(270 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),261- 'utf-16-le', 'strict', line_buffering=True)271+ "utf-16-le",272+ "strict",273+ line_buffering=True,274+ )275 return ConsoleStream(text_stream, buffer_stream)276 277 278 def _get_text_stdout(buffer_stream):279 text_stream = _NonClosingTextIOWrapper(280 io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),268- 'utf-16-le', 'strict', line_buffering=True)281+ "utf-16-le",282+ "strict",283+ line_buffering=True,284+ )285 return ConsoleStream(text_stream, buffer_stream)286 287 288 def _get_text_stderr(buffer_stream):289 text_stream = _NonClosingTextIOWrapper(290 io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),275- 'utf-16-le', 'strict', line_buffering=True)291+ "utf-16-le",292+ "strict",293+ line_buffering=True,294+ )295 return ConsoleStream(text_stream, buffer_stream)296 297 298 if PY2:299+300 def _hash_py_argv():281- return zlib.crc32('\x00'.join(sys.argv[1:]))301+ return zlib.crc32("\x00".join(sys.argv[1:]))302 303 _initial_argv_hash = _hash_py_argv()304 305 def _get_windows_argv():6 unmodified lines312 finally:313 LocalFree(argv_unicode)314 del argv_unicode315 296- if not hasattr(sys, 'frozen'):316+ if not hasattr(sys, "frozen"):317 argv = argv[1:]318 while len(argv) > 0:319 arg = argv[0]300- if not arg.startswith('-') or arg == '-':320+ if not arg.startswith("-") or arg == "-":321 break322 argv = argv[1:]303- if arg.startswith(('-c', '-m')):323+ if arg.startswith(("-c", "-m")):324 break325 326 return argv[1:]327 5 unmodified lines333 }334 335 336 def _is_console(f):317- if not hasattr(f, 'fileno'):337+ if not hasattr(f, "fileno"):338 return False339 340 try:341 fileno = f.fileno()4 unmodified lines346 return bool(GetConsoleMode(handle, byref(DWORD())))347 348 349 def _get_windows_console_stream(f, encoding, errors):330- if get_buffer is not None and \331- encoding in ('utf-16-le', None) \332- and errors in ('strict', None) and \333- _is_console(f):350+ if (351+ get_buffer is not None352+ and encoding in ("utf-16-le", None)353+ and errors in ("strict", None)354+ and _is_console(f)355+ ):356 func = _stream_factories.get(f.fileno())357 if func is not None:358 if not PY2:337- f = getattr(f, 'buffer', None)359+ f = getattr(f, "buffer", None)360 if f is None:361 return None362 else:363 # If we are on Python 2 we need to set the stream that we5 unmodified linesmodified:src/click/core.py+321 added-194 removed
36 unmodified lines37 from .utils import PacifyFlushWrapper38 39 _missing = object()40 41-SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'42-SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'41+SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."42+SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."43 44-DEPRECATED_HELP_NOTICE = ' (DEPRECATED)'45-DEPRECATED_INVOKE_NOTICE = 'DeprecationWarning: ' + \46- 'The command %(name)s is deprecated.'44+DEPRECATED_HELP_NOTICE = " (DEPRECATED)"45+DEPRECATED_INVOKE_NOTICE = (46+ "DeprecationWarning: " + "The command %(name)s is deprecated."47+)48 49 50 def _maybe_show_deprecated_notice(cmd):51 if cmd.deprecated:51- echo(style(DEPRECATED_INVOKE_NOTICE % {'name': cmd.name}, fg='red'), err=True)52+ echo(style(DEPRECATED_INVOKE_NOTICE % {"name": cmd.name}, fg="red"), err=True)53 54 55 def fast_exit(code):56 """Exit without garbage collection, this speeds up exit by about 10ms for6 unmodified lines63 64 def _bashcomplete(cmd, prog_name, complete_var=None):65 """Internal handler for the bash completion support."""66 if complete_var is None:66- complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()67+ complete_var = "_%s_COMPLETE" % (prog_name.replace("-", "_")).upper()68 complete_instr = os.environ.get(complete_var)69 if not complete_instr:70 return71 72 from ._bashcomplete import bashcomplete73+74 if bashcomplete(cmd, prog_name, complete_var, complete_instr):75 fast_exit(1)76 77 78 def _check_multicommand(base_command, cmd_name, cmd, register=False):79 if not base_command.chain or not isinstance(cmd, MultiCommand):80 return81 if register:80- hint = 'It is not possible to add multi commands as children to ' \81- 'another multi command that is in chain mode'82+ hint = (83+ "It is not possible to add multi commands as children to "84+ "another multi command that is in chain mode"85+ )86 else:83- hint = 'Found a multi command as subcommand to a multi command ' \84- 'that is in chain mode. This is not supported'85- raise RuntimeError('%s. Command "%s" is set to chain and "%s" was '86- 'added as subcommand but it in itself is a '87- 'multi command. ("%s" is a %s within a chained '88- '%s named "%s").' % (89- hint, base_command.name, cmd_name,90- cmd_name, cmd.__class__.__name__,91- base_command.__class__.__name__,92- base_command.name))87+ hint = (88+ "Found a multi command as subcommand to a multi command "89+ "that is in chain mode. This is not supported"90+ )91+ raise RuntimeError(92+ '%s. Command "%s" is set to chain and "%s" was '93+ "added as subcommand but it in itself is a "94+ 'multi command. ("%s" is a %s within a chained '95+ '%s named "%s").'96+ % (97+ hint,98+ base_command.name,99+ cmd_name,100+ cmd_name,101+ cmd.__class__.__name__,102+ base_command.__class__.__name__,103+ base_command.name,104+ )105+ )106 107 108 def batch(iterable, batch_size):109 return list(zip(*repeat(iter(iterable), batch_size)))110 111 112 def invoke_param_callback(callback, ctx, param, value):100- code = getattr(callback, '__code__', None)101- args = getattr(code, 'co_argcount', 3)113+ code = getattr(callback, "__code__", None)114+ args = getattr(code, "co_argcount", 3)115 116 if args < 3:117 # This will become a warning in Click 3.0:118 from warnings import warn106- warn(Warning('Invoked legacy parameter callback "%s". The new '107- 'signature for such callbacks starting with '108- 'click 2.0 is (ctx, param, value).'109- % callback), stacklevel=3)119+120+ warn(121+ Warning(122+ 'Invoked legacy parameter callback "%s". The new '123+ "signature for such callbacks starting with "124+ "click 2.0 is (ctx, param, value)." % callback125+ ),126+ stacklevel=3,127+ )128 return callback(ctx, value)129 return callback(ctx, param, value)130 131 20 unmodified lines152 """Given a sequence of parameters in the order as should be considered153 for processing and an iterable of parameters that exist, this returns154 a list in the correct order as they should be processed.155 """156+157 def sort_key(item):158 try:159 idx = invocation_order.index(item)160 except ValueError:142- idx = float('inf')161+ idx = float("inf")162 return (not item.is_eager, idx)163 164 return sorted(declaration_order, key=sort_key)165 83 unmodified lines249 Even if an option is later created with show_default=False,250 this command-level setting overrides it.251 """252 234- def __init__(self, command, parent=None, info_name=None, obj=None,235- auto_envvar_prefix=None, default_map=None,236- terminal_width=None, max_content_width=None,237- resilient_parsing=False, allow_extra_args=None,238- allow_interspersed_args=None,239- ignore_unknown_options=None, help_option_names=None,240- token_normalize_func=None, color=None, show_default=None):253+ def __init__(254+ self,255+ command,256+ parent=None,257+ info_name=None,258+ obj=None,259+ auto_envvar_prefix=None,260+ default_map=None,261+ terminal_width=None,262+ max_content_width=None,263+ resilient_parsing=False,264+ allow_extra_args=None,265+ allow_interspersed_args=None,266+ ignore_unknown_options=None,267+ help_option_names=None,268+ token_normalize_func=None,269+ color=None,270+ show_default=None,271+ ):272 #: the parent context or `None` if none exists.273 self.parent = parent274 #: the :class:`Command` for this context.275 self.command = command12 unmodified lines288 if obj is None and parent is not None:289 obj = parent.obj290 #: the user object stored.291 self.obj = obj261- self._meta = getattr(parent, 'meta', {})292+ self._meta = getattr(parent, "meta", {})293 294 #: A dictionary (-like object) with defaults for parameters.295+ if (264- if default_map is None \265- and parent is not None \266- and parent.default_map is not None:296+ default_map is None297+ and parent is not None298+ and parent.default_map is not None299+ ):300 default_map = parent.default_map.get(info_name)301 self.default_map = default_map302 303 #: This flag indicates if a subcommand is going to be executed. A50 unmodified lines354 if help_option_names is None:355 if parent is not None:356 help_option_names = parent.help_option_names357 else:325- help_option_names = ['--help']358+ help_option_names = ["--help"]359 360 #: The names for the help options.361 self.help_option_names = help_option_names362 12 unmodified lines375 # If there is no envvar prefix yet, but the parent has one and376 # the command on this level has a name, we can expand the envvar377 # prefix automatically.378 if auto_envvar_prefix is None:346- if parent is not None \347- and parent.auto_envvar_prefix is not None and \348- self.info_name is not None:349- auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,350- self.info_name.upper())379+ if (380+ parent is not None381+ and parent.auto_envvar_prefix is not None382+ and self.info_name is not None383+ ):384+ auto_envvar_prefix = "%s_%s" % (385+ parent.auto_envvar_prefix,386+ self.info_name.upper(),387+ )388 else:389 auto_envvar_prefix = auto_envvar_prefix.upper()390 if auto_envvar_prefix is not None:391 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")88 unmodified lines480 return self._meta481 482 def make_formatter(self):483 """Creates the formatter for the help and usage output."""447- return HelpFormatter(width=self.terminal_width,448- max_width=self.max_content_width)484+ return HelpFormatter(485+ width=self.terminal_width, max_width=self.max_content_width486+ )487 488 def call_on_close(self, f):489 """This decorator remembers a function as callback that should be490 executed when the context tears down. This is most useful to bind17 unmodified lines508 """The computed command path. This is used for the ``usage``509 information on the help page. It's automatically created by510 combining the info names of the chain of contexts to the root.511 """474- rv = ''512+ rv = ""513 if self.info_name is not None:514 rv = self.info_name515 if self.parent is not None:478- rv = self.parent.command_path + ' ' + rv516+ rv = self.parent.command_path + " " + rv517 return rv.lstrip()518 519 def find_root(self):520 """Finds the outermost context."""83 unmodified lines604 other_cmd = callback605 callback = other_cmd.callback606 ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)607 if callback is None:570- raise TypeError('The given command does not have a '571- 'callback that can be invoked.')608+ raise TypeError(609+ "The given command does not have a callback that can be invoked."610+ )611 612 for param in other_cmd.params:613 if param.name not in kwargs and param.expose_value:614 kwargs[param.name] = param.get_default(ctx)12 unmodified lines627 628 # It's also possible to invoke another command which might or629 # might not have a callback.630 if not isinstance(cmd, Command):592- raise TypeError('Callback is not a command.')631+ raise TypeError("Callback is not a command.")632 633 for param in self.params:634 if param not in kwargs:635 kwargs[param] = self.params[param]21 unmodified lines657 :param name: the name of the command to use unless a group overrides it.658 :param context_settings: an optional dictionary with defaults that are659 passed to the context object.660 """661+662 #: the default for the :attr:`Context.allow_extra_args` flag.663 allow_extra_args = False664 #: the default for the :attr:`Context.allow_interspersed_args` flag.665 allow_interspersed_args = True14 unmodified lines680 def __repr__(self):681 return "<%s %s>" % (self.__class__.__name__, self.name)682 683 def get_usage(self, ctx):644- raise NotImplementedError('Base commands cannot get usage')684+ raise NotImplementedError("Base commands cannot get usage")685 686 def get_help(self, ctx):647- raise NotImplementedError('Base commands cannot get help')687+ raise NotImplementedError("Base commands cannot get help")688 689 def make_context(self, info_name, args, parent=None, **extra):690 """This function when given an info name and arguments will kick691 off the parsing and create a new :class:`Context`. It does not21 unmodified lines713 """Given a context and a list of arguments this creates the parser714 and parses the arguments, then modifies the context as necessary.715 This is automatically invoked by :meth:`make_context`.716 """677- raise NotImplementedError('Base commands do not know how to parse '678- 'arguments.')717+ raise NotImplementedError(718+ "Base commands do not know how to parse arguments."719+ )720 721 def invoke(self, ctx):722 """Given a context, this invokes the command. The default723 implementation is raising a not implemented error.724 """684- raise NotImplementedError('Base commands are not invokable by default')725+ raise NotImplementedError("Base commands are not invokable by default")726 686- def main(self, args=None, prog_name=None, complete_var=None,687- standalone_mode=True, **extra):727+ def main(728+ self,729+ args=None,730+ prog_name=None,731+ complete_var=None,732+ standalone_mode=True,733+ **extra734+ ):735 """This is the way to invoke a script with all the bells and736 whistles as a command line application. This will always terminate737 the application after a call. If this is not wanted, ``SystemExit``738 needs to be caught.38 unmodified lines777 else:778 args = list(args)779 780 if prog_name is None:734- prog_name = make_str(os.path.basename(735- sys.argv and sys.argv[0] or __file__))781+ prog_name = make_str(os.path.basename(sys.argv and sys.argv[0] or __file__))782 783 # Hook for the Bash completion. This only activates if the Bash784 # completion is actually enabled, otherwise this is quite a fast785 # noop.43 unmodified lines829 return e.exit_code830 except Abort:831 if not standalone_mode:832 raise787- echo('Aborted!', file=sys.stderr)833+ echo("Aborted!", file=sys.stderr)834 sys.exit(1)835 836 def __call__(self, *args, **kwargs):837 """Alias for :meth:`main`."""32 unmodified lines870 :param deprecated: issues a message indicating that871 the command is deprecated.872 """873 828- def __init__(self, name, context_settings=None, callback=None,829- params=None, help=None, epilog=None, short_help=None,830- options_metavar='[OPTIONS]', add_help_option=True,831- no_args_is_help=False, hidden=False, deprecated=False):874+ def __init__(875+ self,876+ name,877+ context_settings=None,878+ callback=None,879+ params=None,880+ help=None,881+ epilog=None,882+ short_help=None,883+ options_metavar="[OPTIONS]",884+ add_help_option=True,885+ no_args_is_help=False,886+ hidden=False,887+ deprecated=False,888+ ):889 BaseCommand.__init__(self, name, context_settings)890 #: the callback to execute when the command fires. This might be891 #: `None` in which case nothing happens.892 self.callback = callback2 unmodified lines895 #: will automatically be handled before non eager ones.896 self.params = params or []897 # if a form feed (page break) is found in the help text, truncate help898 # text to the content preceding the first form feed842- if help and '\f' in help:843- help = help.split('\f', 1)[0]899+ if help and "\f" in help:900+ help = help.split("\f", 1)[0]901 self.help = help902 self.epilog = epilog903 self.options_metavar = options_metavar904 self.short_help = short_help8 unmodified lines913 Calls :meth:`format_usage` internally.914 """915 formatter = ctx.make_formatter()916 self.format_usage(ctx, formatter)860- return formatter.getvalue().rstrip('\n')917+ return formatter.getvalue().rstrip("\n")918 919 def get_params(self, ctx):920 rv = self.params921 help_option = self.get_help_option(ctx)6 unmodified lines928 929 This is a low-level method called by :meth:`get_usage`.930 """931 pieces = self.collect_usage_pieces(ctx)875- formatter.write_usage(ctx.command_path, ' '.join(pieces))932+ formatter.write_usage(ctx.command_path, " ".join(pieces))933 934 def collect_usage_pieces(self, ctx):935 """Returns all the pieces that go into the usage line and returns936 it as a list of strings.20 unmodified lines957 def show_help(ctx, param, value):958 if value and not ctx.resilient_parsing:959 echo(ctx.get_help(), color=ctx.color)960 ctx.exit()904- return Option(help_options, is_flag=True,905- is_eager=True, expose_value=False,906- callback=show_help,907- help='Show this message and exit.')961 962+ return Option(963+ help_options,964+ is_flag=True,965+ is_eager=True,966+ expose_value=False,967+ callback=show_help,968+ help="Show this message and exit.",969+ )970+971 def make_parser(self, ctx):972 """Creates the underlying option parser for this command."""973 parser = OptionParser(ctx)974 for param in self.get_params(ctx):6 unmodified lines981 Calls :meth:`format_help` internally.982 """983 formatter = ctx.make_formatter()984 self.format_help(ctx, formatter)923- return formatter.getvalue().rstrip('\n')985+ return formatter.getvalue().rstrip("\n")986 987 def get_short_help_str(self, limit=45):988 """Gets short help for the command or makes it by shortening the long help string."""927- return self.short_help or self.help and make_default_short_help(self.help, limit) or ''989+ return (990+ self.short_help991+ or self.help992+ and make_default_short_help(self.help, limit)993+ or ""994+ )995 996 def format_help(self, ctx, formatter):997 """Writes the help into the formatter if it exists.998 33 unmodified lines1032 if rv is not None:1033 opts.append(rv)1034 1035 if opts:969- with formatter.section('Options'):1036+ with formatter.section("Options"):1037 formatter.write_dl(opts)1038 1039 def format_epilog(self, ctx, formatter):1040 """Writes the epilog into the formatter if it exists."""9 unmodified lines1050 1051 parser = self.make_parser(ctx)1052 opts, args, param_order = parser.parse_args(args=args)1053 987- for param in iter_params_for_processing(988- param_order, self.get_params(ctx)):1054+ for param in iter_params_for_processing(param_order, self.get_params(ctx)):1055 value, args = param.handle_parse_result(ctx, opts, args)1056 1057 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:992- ctx.fail('Got unexpected extra argument%s (%s)'993- % (len(args) != 1 and 's' or '',994- ' '.join(map(make_str, args))))1058+ ctx.fail(1059+ "Got unexpected extra argument%s (%s)"1060+ % (len(args) != 1 and "s" or "", " ".join(map(make_str, args)))1061+ )1062 1063 ctx.args = args1064 return args1065 28 unmodified lines1094 multiple commands to be chained together.1095 :param result_callback: the result callback to attach to this multi1096 command.1097 """1098+1099 allow_extra_args = True1100 allow_interspersed_args = False1101 1034- def __init__(self, name=None, invoke_without_command=False,1035- no_args_is_help=None, subcommand_metavar=None,1036- chain=False, result_callback=None, **attrs):1102+ def __init__(1103+ self,1104+ name=None,1105+ invoke_without_command=False,1106+ no_args_is_help=None,1107+ subcommand_metavar=None,1108+ chain=False,1109+ result_callback=None,1110+ **attrs1111+ ):1112 Command.__init__(self, name, **attrs)1113 if no_args_is_help is None:1114 no_args_is_help = not invoke_without_command1115 self.no_args_is_help = no_args_is_help11 unmodified lines1127 1128 if self.chain:1129 for param in self.params:1130 if isinstance(param, Argument) and not param.required:1056- raise RuntimeError('Multi commands in chain mode cannot '1057- 'have optional arguments.')1131+ raise RuntimeError(1132+ "Multi commands in chain mode cannot "1133+ "have optional arguments."1134+ )1135 1136 def collect_usage_pieces(self, ctx):1137 rv = Command.collect_usage_pieces(self, ctx)1138 rv.append(self.subcommand_metavar)27 unmodified lines1166 1167 :param replace: if set to `True` an already existing result1168 callback will be removed.1169 """1170+1171 def decorator(f):1172 old_callback = self.result_callback1173 if old_callback is None or replace:1174 self.result_callback = f1175 return f1176+1177 def function(__value, *args, **kwargs):1099- return f(old_callback(__value, *args, **kwargs),1100- *args, **kwargs)1178+ return f(old_callback(__value, *args, **kwargs), *args, **kwargs)1179+1180 self.result_callback = rv = update_wrapper(function, f)1181 return rv1182+1183 return decorator1184 1185 def format_commands(self, ctx, formatter):1186 """Extra format methods for multi methods that adds all the commands19 unmodified lines1206 help = cmd.get_short_help_str(limit)1207 rows.append((subcommand, help))1208 1209 if rows:1130- with formatter.section('Commands'):1210+ with formatter.section("Commands"):1211 formatter.write_dl(rows)1212 1213 def parse_args(self, ctx, args):1214 if not args and self.no_args_is_help and not ctx.resilient_parsing:11 unmodified lines1226 1227 def invoke(self, ctx):1228 def _process_result(value):1229 if self.result_callback is not None:1150- value = ctx.invoke(self.result_callback, value,1151- **ctx.params)1230+ value = ctx.invoke(self.result_callback, value, **ctx.params)1231 return value1232 1233 if not ctx.protected_args:1234 # If we are invoked without command the chain flag controls7 unmodified lines1242 return Command.invoke(self, ctx)1243 with ctx:1244 Command.invoke(self, ctx)1245 return _process_result([])1167- ctx.fail('Missing command.')1246+ ctx.fail("Missing command.")1247 1248 # Fetch args back out1249 args = ctx.protected_args + ctx.args1250 ctx.args = []18 unmodified lines1269 # know the subcommands yet, the invoked subcommand attribute is1270 # set to ``*`` to inform the command that subcommands are executed1271 # but nothing else.1272 with ctx:1194- ctx.invoked_subcommand = args and '*' or None1273+ ctx.invoked_subcommand = args and "*" or None1274 Command.invoke(self, ctx)1275 1276 # Otherwise we make every single context and invoke them in a1277 # chain. In that case the return value to the result processor1278 # is the list of all invoked subcommand's results.1279 contexts = []1280 while args:1281 cmd_name, cmd, args = self.resolve_command(ctx, args)1282+ sub_ctx = cmd.make_context(1283+ cmd_name,1284+ args,1203- sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,1204- allow_extra_args=True,1205- allow_interspersed_args=False)1285+ parent=ctx,1286+ allow_extra_args=True,1287+ allow_interspersed_args=False,1288+ )1289 contexts.append(sub_ctx)1290 args, sub_ctx.args = sub_ctx.args, []1291 1292 rv = []58 unmodified lines1351 is not provided, the name of the command is used.1352 """1353 name = name or cmd.name1354 if name is None:1272- raise TypeError('Command has no name.')1355+ raise TypeError("Command has no name.")1356 _check_multicommand(self, name, cmd, register=True)1357 self.commands[name] = cmd1358 1359 def command(self, *args, **kwargs):1 unmodified line1361 the group. This takes the same arguments as :func:`command` but1362 immediately registers the created command with this instance by1363 calling into :meth:`add_command`.1364 """1365+1366 def decorator(f):1367 cmd = command(*args, **kwargs)(f)1368 self.add_command(cmd)1369 return cmd1370+1371 return decorator1372 1373 def group(self, *args, **kwargs):1374 """A shortcut decorator for declaring and attaching a group to1375 the group. This takes the same arguments as :func:`group` but1376 immediately registers the created command with this instance by1377 calling into :meth:`add_command`.1378 """1379+1380 def decorator(f):1381 cmd = group(*args, **kwargs)(f)1382 self.add_command(cmd)1383 return cmd1384+1385 return decorator1386 1387 def get_command(self, ctx, cmd_name):1388 return self.commands.get(cmd_name)78 unmodified lines1467 Changed signature for parameter callback to also be passed the1468 parameter. The old callback format will still work, but it will1469 raise a warning to give you a chance to migrate the code easier.1470 """1384- param_type_name = 'parameter'1471+ param_type_name = "parameter"1472 1386- def __init__(self, param_decls=None, type=None, required=False,1387- default=None, callback=None, nargs=None, metavar=None,1388- expose_value=True, is_eager=False, envvar=None,1389- autocompletion=None):1390- self.name, self.opts, self.secondary_opts = \1391- self._parse_decls(param_decls or (), expose_value)1473+ def __init__(1474+ self,1475+ param_decls=None,1476+ type=None,1477+ required=False,1478+ default=None,1479+ callback=None,1480+ nargs=None,1481+ metavar=None,1482+ expose_value=True,1483+ is_eager=False,1484+ envvar=None,1485+ autocompletion=None,1486+ ):1487+ self.name, self.opts, self.secondary_opts = self._parse_decls(1488+ param_decls or (), expose_value1489+ )1490 1491 self.type = convert_type(type, default)1492 1493 # Default nargs to what the type tells us if we have that31 unmodified lines1525 metavar = self.type.get_metavar(self)1526 if metavar is None:1527 metavar = self.type.name.upper()1528 if self.nargs != 1:1431- metavar += '...'1529+ metavar += "..."1530 return metavar1531 1532 def get_default(self, ctx):1533 """Given a context variable this calculates the default value."""21 unmodified lines1555 well as composite types.1556 """1557 if self.type.is_composite:1558 if self.nargs <= 1:1461- raise TypeError('Attempted to invoke composite type '1462- 'but nargs has been set to %s. This is '1463- 'not supported; nargs needs to be set to '1464- 'a fixed value > 1.' % self.nargs)1559+ raise TypeError(1560+ "Attempted to invoke composite type "1561+ "but nargs has been set to %s. This is "1562+ "not supported; nargs needs to be set to "1563+ "a fixed value > 1." % self.nargs1564+ )1565 if self.multiple:1566 return tuple(self.type(x or (), self, ctx) for x in value or ())1567 return self.type(value or (), self, ctx)1568 1569 def _convert(value, level):1570 if level == 0:1571 return self.type(value, self, ctx)1572 return tuple(_convert(x, level - 1) for x in value or ())1573+1574 return _convert(value, (self.nargs != 1) + bool(self.multiple))1575 1576 def process_value(self, ctx, value):1577 """Given a value and context this runs the logic to convert the54 unmodified lines1632 raise1633 value = None1634 if self.callback is not None:1635 try:1535- value = invoke_param_callback(1536- self.callback, ctx, self, value)1636+ value = invoke_param_callback(self.callback, ctx, self, value)1637 except Exception:1638 if not ctx.resilient_parsing:1639 raise1640 11 unmodified lines1652 """Get a stringified version of the param for use in error messages to1653 indicate which param caused the error.1654 """1655 hint_list = self.opts or [self.human_readable_name]1556- return ' / '.join('"%s"' % x for x in hint_list)1656+ return " / ".join('"%s"' % x for x in hint_list)1657 1658 1659 class Option(Parameter):1660 """Options are usually optional values on the command line and32 unmodified lines1693 context.1694 :param help: the help string.1695 :param hidden: hide this option from help outputs.1696 """1597- param_type_name = 'option'1697 1599- def __init__(self, param_decls=None, show_default=False,1600- prompt=False, confirmation_prompt=False,1601- hide_input=False, is_flag=None, flag_value=None,1602- multiple=False, count=False, allow_from_autoenv=True,1603- type=None, help=None, hidden=False, show_choices=True,1604- show_envvar=False, **attrs):1605- default_is_missing = attrs.get('default', _missing) is _missing1698+ param_type_name = "option"1699+1700+ def __init__(1701+ self,1702+ param_decls=None,1703+ show_default=False,1704+ prompt=False,1705+ confirmation_prompt=False,1706+ hide_input=False,1707+ is_flag=None,1708+ flag_value=None,1709+ multiple=False,1710+ count=False,1711+ allow_from_autoenv=True,1712+ type=None,1713+ help=None,1714+ hidden=False,1715+ show_choices=True,1716+ show_envvar=False,1717+ **attrs1718+ ):1719+ default_is_missing = attrs.get("default", _missing) is _missing1720 Parameter.__init__(self, param_decls, type=type, **attrs)1721 1722 if prompt is True:1609- prompt_text = self.name.replace('_', ' ').capitalize()1723+ prompt_text = self.name.replace("_", " ").capitalize()1724 elif prompt is False:1725 prompt_text = None1726 else:1727 prompt_text = prompt13 unmodified lines1741 if flag_value is None:1742 flag_value = not self.default1743 self.is_flag = is_flag1744 self.flag_value = flag_value1631- if self.is_flag and isinstance(self.flag_value, bool) \1632- and type in [None, bool]:1745+ if self.is_flag and isinstance(self.flag_value, bool) and type in [None, bool]:1746 self.type = BOOL1747 self.is_bool_flag = True1748 else:1749 self.is_bool_flag = False15 unmodified lines1765 1766 # Sanity check for stuff we don't support1767 if __debug__:1768 if self.nargs < 0:1656- raise TypeError('Options cannot have nargs < 0')1769+ raise TypeError("Options cannot have nargs < 0")1770 if self.prompt and self.is_flag and not self.is_bool_flag:1658- raise TypeError('Cannot prompt for flags that are not bools.')1771+ raise TypeError("Cannot prompt for flags that are not bools.")1772 if not self.is_bool_flag and self.secondary_opts:1660- raise TypeError('Got secondary option for non boolean flag.')1661- if self.is_bool_flag and self.hide_input \1662- and self.prompt is not None:1663- raise TypeError('Hidden input does not work with boolean '1664- 'flag prompts.')1773+ raise TypeError("Got secondary option for non boolean flag.")1774+ if self.is_bool_flag and self.hide_input and self.prompt is not None:1775+ raise TypeError(1776+ "Hidden input does not work with boolean flag prompts."1777+ )1778 if self.count:1779 if self.multiple:1667- raise TypeError('Options cannot be multiple and count '1668- 'at the same time.')1780+ raise TypeError(1781+ "Options cannot be multiple and count at the same time."1782+ )1783 elif self.is_flag:1670- raise TypeError('Options cannot be count and flags at '1671- 'the same time.')1784+ raise TypeError(1785+ "Options cannot be count and flags at the same time."1786+ )1787 1788 def _parse_decls(self, decls, expose_value):1789 opts = []1790 secondary_opts = []2 unmodified lines1793 1794 for decl in decls:1795 if isidentifier(decl):1796 if name is not None:1682- raise TypeError('Name defined twice')1797+ raise TypeError("Name defined twice")1798 name = decl1799 else:1685- split_char = decl[:1] == '/' and ';' or '/'1800+ split_char = decl[:1] == "/" and ";" or "/"1801 if split_char in decl:1802 first, second = decl.split(split_char, 1)1803 first = first.rstrip()1804 if first:7 unmodified lines1812 opts.append(decl)1813 1814 if name is None and possible_names:1815 possible_names.sort(key=lambda x: -len(x[0])) # group long options first1701- name = possible_names[0][1].replace('-', '_').lower()1816+ name = possible_names[0][1].replace("-", "_").lower()1817 if not isidentifier(name):1818 name = None1819 1820 if name is None:1821 if not expose_value:1822 return None, opts, secondary_opts1708- raise TypeError('Could not determine name for option')1823+ raise TypeError("Could not determine name for option")1824 1825 if not opts and not secondary_opts:1711- raise TypeError('No options defined but a name was passed (%s). '1712- 'Did you mean to declare an argument instead '1713- 'of an option?' % name)1826+ raise TypeError(1827+ "No options defined but a name was passed (%s). "1828+ "Did you mean to declare an argument instead "1829+ "of an option?" % name1830+ )1831 1832 return name, opts, secondary_opts1833 1834 def add_to_parser(self, parser, ctx):1835 kwargs = {1719- 'dest': self.name,1720- 'nargs': self.nargs,1721- 'obj': self,1836+ "dest": self.name,1837+ "nargs": self.nargs,1838+ "obj": self,1839 }1840 1841 if self.multiple:1725- action = 'append'1842+ action = "append"1843 elif self.count:1727- action = 'count'1844+ action = "count"1845 else:1729- action = 'store'1846+ action = "store"1847 1848 if self.is_flag:1732- kwargs.pop('nargs', None)1849+ kwargs.pop("nargs", None)1850 if self.is_bool_flag and self.secondary_opts:1734- parser.add_option(self.opts, action=action + '_const',1735- const=True, **kwargs)1736- parser.add_option(self.secondary_opts, action=action +1737- '_const', const=False, **kwargs)1851+ parser.add_option(1852+ self.opts, action=action + "_const", const=True, **kwargs1853+ )1854+ parser.add_option(1855+ self.secondary_opts, action=action + "_const", const=False, **kwargs1856+ )1857 else:1739- parser.add_option(self.opts, action=action + '_const',1740- const=self.flag_value,1741- **kwargs)1858+ parser.add_option(1859+ self.opts, action=action + "_const", const=self.flag_value, **kwargs1860+ )1861 else:1743- kwargs['action'] = action1862+ kwargs["action"] = action1863 parser.add_option(self.opts, **kwargs)1864 1865 def get_help_record(self, ctx):1866 if self.hidden:4 unmodified lines1871 rv, any_slashes = join_options(opts)1872 if any_slashes:1873 any_prefix_is_slash[:] = [True]1874 if not self.is_flag and not self.count:1756- rv += ' ' + self.make_metavar()1875+ rv += " " + self.make_metavar()1876 return rv1877 1878 rv = [_write_opts(self.opts)]1879 if self.secondary_opts:1880 rv.append(_write_opts(self.secondary_opts))1881 1763- help = self.help or ''1882+ help = self.help or ""1883 extra = []1884 if self.show_envvar:1885 envvar = self.envvar1886 if envvar is None:1768- if self.allow_from_autoenv and \1769- ctx.auto_envvar_prefix is not None:1770- envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1887+ if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1888+ envvar = "%s_%s" % (ctx.auto_envvar_prefix, self.name.upper())1889 if envvar is not None:1772- extra.append('env var: %s' % (1773- ', '.join('%s' % d for d in envvar)1774- if isinstance(envvar, (list, tuple))1775- else envvar, ))1776- if self.default is not None and \1777- (self.show_default or ctx.show_default):1890+ extra.append(1891+ "env var: %s"1892+ % (1893+ ", ".join("%s" % d for d in envvar)1894+ if isinstance(envvar, (list, tuple))1895+ else envvar,1896+ )1897+ )1898+ if self.default is not None and (self.show_default or ctx.show_default):1899 if isinstance(self.show_default, string_types):1779- default_string = '({})'.format(self.show_default)1900+ default_string = "({})".format(self.show_default)1901 elif isinstance(self.default, (list, tuple)):1781- default_string = ', '.join('%s' % d for d in self.default)1902+ default_string = ", ".join("%s" % d for d in self.default)1903 elif inspect.isfunction(self.default):1904 default_string = "(dynamic)"1905 else:1906 default_string = self.default1786- extra.append('default: {}'.format(default_string))1907+ extra.append("default: {}".format(default_string))1908 1909 if self.required:1789- extra.append('required')1910+ extra.append("required")1911 if extra:1791- help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))1912+ help = "%s[%s]" % (help and help + " " or "", "; ".join(extra))1913 1793- return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help)1914+ return ((any_prefix_is_slash and "; " or " / ").join(rv), help)1915 1916 def get_default(self, ctx):1917 # If we're a non boolean flag our default is more complex because1918 # we need to look at all flags in the same group to figure out19 unmodified lines1938 # differently.1939 if self.is_bool_flag:1940 return confirm(self.prompt, default)1941 1942+ return prompt(1943+ self.prompt,1944+ default=default,1945+ type=self.type,1821- return prompt(self.prompt, default=default, type=self.type,1822- hide_input=self.hide_input, show_choices=self.show_choices,1823- confirmation_prompt=self.confirmation_prompt,1824- value_proc=lambda x: self.process_value(ctx, x))1946+ hide_input=self.hide_input,1947+ show_choices=self.show_choices,1948+ confirmation_prompt=self.confirmation_prompt,1949+ value_proc=lambda x: self.process_value(ctx, x),1950+ )1951 1952 def resolve_envvar_value(self, ctx):1953 rv = Parameter.resolve_envvar_value(self, ctx)1954 if rv is not None:1955 return rv1830- if self.allow_from_autoenv and \1831- ctx.auto_envvar_prefix is not None:1832- envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1956+ if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1957+ envvar = "%s_%s" % (ctx.auto_envvar_prefix, self.name.upper())1958 return os.environ.get(envvar)1959 1960 def value_from_envvar(self, ctx):1961 rv = self.resolve_envvar_value(ctx)6 unmodified lines1968 rv = batch(rv, self.nargs)1969 return rv1970 1971 def full_process_value(self, ctx, value):1847- if value is None and self.prompt is not None \1848- and not ctx.resilient_parsing:1972+ if value is None and self.prompt is not None and not ctx.resilient_parsing:1973 return self.prompt_for_value(ctx)1974 return Parameter.full_process_value(self, ctx, value)1975 1976 3 unmodified lines1980 and are required by default.1981 1982 All parameters are passed onwards to the parameter constructor.1983 """1860- param_type_name = 'argument'1984 1985+ param_type_name = "argument"1986+1987 def __init__(self, param_decls, required=None, **attrs):1988 if required is None:1864- if attrs.get('default') is not None:1989+ if attrs.get("default") is not None:1990 required = False1991 else:1867- required = attrs.get('nargs', 1) > 01992+ required = attrs.get("nargs", 1) > 01993 Parameter.__init__(self, param_decls, required=required, **attrs)1994 if self.default is not None and self.nargs < 0:1870- raise TypeError('nargs=-1 in combination with a default value '1871- 'is not supported.')1995+ raise TypeError(1996+ "nargs=-1 in combination with a default value is not supported."1997+ )1998 1999 @property2000 def human_readable_name(self):2001 if self.metavar is not None:6 unmodified lines2008 var = self.type.get_metavar(self)2009 if not var:2010 var = self.name.upper()2011 if not self.required:1886- var = '[%s]' % var2012+ var = "[%s]" % var2013 if self.nargs != 1:1888- var += '...'2014+ var += "..."2015 return var2016 2017 def _parse_decls(self, decls, expose_value):2018 if not decls:2019 if not expose_value:2020 return None, [], []1895- raise TypeError('Could not determine name for argument')2021+ raise TypeError("Could not determine name for argument")2022 if len(decls) == 1:2023 name = arg = decls[0]1898- name = name.replace('-', '_').lower()2024+ name = name.replace("-", "_").lower()2025 else:1900- raise TypeError('Arguments take exactly one '1901- 'parameter declaration, got %d' % len(decls))2026+ raise TypeError(2027+ "Arguments take exactly one "2028+ "parameter declaration, got %d" % len(decls)2029+ )2030 return name, [arg], []2031 2032 def get_usage_pieces(self, ctx):2033 return [self.make_metavar()]1 unmodified line2035 def get_error_hint(self, ctx):2036 return '"%s"' % self.make_metavar()2037 2038 def add_to_parser(self, parser, ctx):1911- parser.add_argument(dest=self.name, nargs=self.nargs,1912- obj=self)2039+ parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)2040 2041 2042 # Circular dependency between decorators and core2043 from .decorators import command, groupmodified:src/click/decorators.py+72 added-49 removed
10 unmodified lines11 def pass_context(f):12 """Marks a callback as wanting to receive the current context13 object as first argument.14 """15+16 def new_func(*args, **kwargs):17 return f(get_current_context(), *args, **kwargs)18+19 return update_wrapper(new_func, f)20 21 22 def pass_obj(f):23 """Similar to :func:`pass_context`, but only pass the object on the24 context onwards (:attr:`Context.obj`). This is useful if that object25 represents the state of a nested system.26 """27+28 def new_func(*args, **kwargs):29 return f(get_current_context().obj, *args, **kwargs)30+31 return update_wrapper(new_func, f)32 33 34 def make_pass_decorator(object_type, ensure=False):17 unmodified lines52 :param object_type: the type of the object to pass.53 :param ensure: if set to `True`, a new object will be created and54 remembered on the context if it's not there yet.55 """56+57 def decorator(f):58 def new_func(*args, **kwargs):59 ctx = get_current_context()60 if ensure:61 obj = ctx.ensure_object(object_type)62 else:63 obj = ctx.find_object(object_type)64 if obj is None:60- raise RuntimeError('Managed to invoke callback without a '61- 'context object of type %r existing'62- % object_type.__name__)65+ raise RuntimeError(66+ "Managed to invoke callback without a "67+ "context object of type %r existing" % object_type.__name__68+ )69 return ctx.invoke(f, obj, *args, **kwargs)70+71 return update_wrapper(new_func, f)72+73 return decorator74 75 76 def _make_command(f, name, attrs, cls):77 if isinstance(f, Command):70- raise TypeError('Attempted to convert a callback into a '71- 'command twice.')78+ raise TypeError("Attempted to convert a callback into a command twice.")79 try:80 params = f.__click_params__81 params.reverse()82 del f.__click_params__83 except AttributeError:84 params = []78- help = attrs.get('help')85+ help = attrs.get("help")86 if help is None:87 help = inspect.getdoc(f)88 if isinstance(help, bytes):82- help = help.decode('utf-8')89+ help = help.decode("utf-8")90 else:91 help = inspect.cleandoc(help)85- attrs['help'] = help92+ attrs["help"] = help93 _check_for_unicode_literals()87- return cls(name=name or f.__name__.lower().replace('_', '-'),88- callback=f, params=params, **attrs)94+ return cls(95+ name=name or f.__name__.lower().replace("_", "-"),96+ callback=f,97+ params=params,98+ **attrs99+ )100 101 102 def command(name=None, cls=None, **attrs):103 r"""Creates a new :class:`Command` and uses the decorated function as16 unmodified lines120 :class:`Command`.121 """122 if cls is None:123 cls = Command124+125 def decorator(f):126 cmd = _make_command(f, name, attrs, cls)127 cmd.__doc__ = f.__doc__128 return cmd129+130 return decorator131 132 133 def group(name=None, **attrs):134 """Creates a new :class:`Group` with a function as callback. This135 works otherwise the same as :func:`command` just that the `cls`136 parameter is set to :class:`Group`.137 """125- attrs.setdefault('cls', Group)138+ attrs.setdefault("cls", Group)139 return command(name, **attrs)140 141 142 def _param_memo(f, param):143 if isinstance(f, Command):144 f.params.append(param)145 else:133- if not hasattr(f, '__click_params__'):146+ if not hasattr(f, "__click_params__"):147 f.__click_params__ = []148 f.__click_params__.append(param)149 150 6 unmodified lines157 158 :param cls: the argument class to instantiate. This defaults to159 :class:`Argument`.160 """161+162 def decorator(f):149- ArgumentClass = attrs.pop('cls', Argument)163+ ArgumentClass = attrs.pop("cls", Argument)164 _param_memo(f, ArgumentClass(param_decls, **attrs))165 return f166+167 return decorator168 169 170 def option(*param_decls, **attrs):5 unmodified lines176 177 :param cls: the option class to instantiate. This defaults to178 :class:`Option`.179 """180+181 def decorator(f):182 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=183 option_attrs = attrs.copy()184 169- if 'help' in option_attrs:170- option_attrs['help'] = inspect.cleandoc(option_attrs['help'])171- OptionClass = option_attrs.pop('cls', Option)185+ if "help" in option_attrs:186+ option_attrs["help"] = inspect.cleandoc(option_attrs["help"])187+ OptionClass = option_attrs.pop("cls", Option)188 _param_memo(f, OptionClass(param_decls, **option_attrs))189 return f190+191 return decorator192 193 194 def confirmation_option(*param_decls, **attrs):12 unmodified lines207 expose_value=False, prompt='Do you want to continue?')208 def dropdb():209 pass210 """211+212 def decorator(f):213 def callback(ctx, param, value):214 if not value:215 ctx.abort()198- attrs.setdefault('is_flag', True)199- attrs.setdefault('callback', callback)200- attrs.setdefault('expose_value', False)201- attrs.setdefault('prompt', 'Do you want to continue?')202- attrs.setdefault('help', 'Confirm the action without prompting.')203- return option(*(param_decls or ('--yes',)), **attrs)(f)216+217+ attrs.setdefault("is_flag", True)218+ attrs.setdefault("callback", callback)219+ attrs.setdefault("expose_value", False)220+ attrs.setdefault("prompt", "Do you want to continue?")221+ attrs.setdefault("help", "Confirm the action without prompting.")222+ return option(*(param_decls or ("--yes",)), **attrs)(f)223+224 return decorator225 226 227 def password_option(*param_decls, **attrs):7 unmodified lines235 hide_input=True)236 def changeadmin(password):237 pass238 """239+240 def decorator(f):220- attrs.setdefault('prompt', True)221- attrs.setdefault('confirmation_prompt', True)222- attrs.setdefault('hide_input', True)223- return option(*(param_decls or ('--password',)), **attrs)(f)241+ attrs.setdefault("prompt", True)242+ attrs.setdefault("confirmation_prompt", True)243+ attrs.setdefault("hide_input", True)244+ return option(*(param_decls or ("--password",)), **attrs)(f)245+246 return decorator247 248 249 def version_option(version=None, *param_decls, **attrs):8 unmodified lines258 (``'%(prog)s, version %(version)s'``)259 :param others: everything else is forwarded to :func:`option`.260 """261 if version is None:240- if hasattr(sys, '_getframe'):241- module = sys._getframe(1).f_globals.get('__name__')262+ if hasattr(sys, "_getframe"):263+ module = sys._getframe(1).f_globals.get("__name__")264 else:243- module = ''265+ module = ""266 267 def decorator(f):246- prog_name = attrs.pop('prog_name', None)247- message = attrs.pop('message', '%(prog)s, version %(version)s')268+ prog_name = attrs.pop("prog_name", None)269+ message = attrs.pop("message", "%(prog)s, version %(version)s")270 271 def callback(ctx, param, value):272 if not value or ctx.resilient_parsing:273 return7 unmodified lines281 except ImportError:282 pass283 else:284 for dist in pkg_resources.working_set:263- scripts = dist.get_entry_map().get('console_scripts') or {}285+ scripts = dist.get_entry_map().get("console_scripts") or {}286 for script_name, entry_point in iteritems(scripts):287 if entry_point.module_name == module:288 ver = dist.version289 break290 if ver is None:269- raise RuntimeError('Could not determine version')270- echo(message % {271- 'prog': prog,272- 'version': ver,273- }, color=ctx.color)291+ raise RuntimeError("Could not determine version")292+ echo(message % {"prog": prog, "version": ver,}, color=ctx.color)293 ctx.exit()294 276- attrs.setdefault('is_flag', True)277- attrs.setdefault('expose_value', False)278- attrs.setdefault('is_eager', True)279- attrs.setdefault('help', 'Show the version and exit.')280- attrs['callback'] = callback281- return option(*(param_decls or ('--version',)), **attrs)(f)295+ attrs.setdefault("is_flag", True)296+ attrs.setdefault("expose_value", False)297+ attrs.setdefault("is_eager", True)298+ attrs.setdefault("help", "Show the version and exit.")299+ attrs["callback"] = callback300+ return option(*(param_decls or ("--version",)), **attrs)(f)301+302 return decorator303 304 305 def help_option(*param_decls, **attrs):5 unmodified lines311 prints in the callback and exits.312 313 All arguments are forwarded to :func:`option`.314 """315+316 def decorator(f):317 def callback(ctx, param, value):318 if value and not ctx.resilient_parsing:319 echo(ctx.get_help(), color=ctx.color)320 ctx.exit()300- attrs.setdefault('is_flag', True)301- attrs.setdefault('expose_value', False)302- attrs.setdefault('help', 'Show this message and exit.')303- attrs.setdefault('is_eager', True)304- attrs['callback'] = callback305- return option(*(param_decls or ('--help',)), **attrs)(f)321+322+ attrs.setdefault("is_flag", True)323+ attrs.setdefault("expose_value", False)324+ attrs.setdefault("help", "Show this message and exit.")325+ attrs.setdefault("is_eager", True)326+ attrs["callback"] = callback327+ return option(*(param_decls or ("--help",)), **attrs)(f)328+329 return decorator330 331 332 # Circular dependencies between core and decorators1 unmodified linemodified:src/click/exceptions.py+32 added-30 removed
4 unmodified lines5 6 7 def _join_param_hints(param_hint):8 if isinstance(param_hint, (tuple, list)):9- return ' / '.join('"%s"' % x for x in param_hint)9+ return " / ".join('"%s"' % x for x in param_hint)10 return param_hint11 12 13 class ClickException(Exception):5 unmodified lines19 def __init__(self, message):20 ctor_msg = message21 if PY2:22 if ctor_msg is not None:23- ctor_msg = ctor_msg.encode('utf-8')23+ ctor_msg = ctor_msg.encode("utf-8")24 Exception.__init__(self, ctor_msg)25 self.message = message26 27 def format_message(self):5 unmodified lines33 if PY2:34 __unicode__ = __str__35 36 def __str__(self):37- return self.message.encode('utf-8')37+ return self.message.encode("utf-8")38 39 def show(self, file=None):40 if file is None:41 file = get_text_stderr()42- echo('Error: %s' % self.format_message(), file=file)42+ echo("Error: %s" % self.format_message(), file=file)43 44 45 class UsageError(ClickException):46 """An internal exception that signals a usage error. This typically2 unmodified lines49 :param message: the error message to display.50 :param ctx: optionally the context that caused this error. Click will51 fill in the context automatically in some situations.52 """53+54 exit_code = 255 56 def __init__(self, message, ctx=None):57 ClickException.__init__(self, message)3 unmodified lines61 def show(self, file=None):62 if file is None:63 file = get_text_stderr()64 color = None64- hint = ''65- if (self.cmd is not None and66- self.cmd.get_help_option(self.ctx) is not None):67- hint = ('Try "%s %s" for help.\n'68- % (self.ctx.command_path, self.ctx.help_option_names[0]))65+ hint = ""66+ if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:67+ hint = 'Try "%s %s" for help.\n' % (68+ self.ctx.command_path,69+ self.ctx.help_option_names[0],70+ )71 if self.ctx is not None:72 color = self.ctx.color71- echo(self.ctx.get_usage() + '\n%s' % hint, file=file, color=color)72- echo('Error: %s' % self.format_message(), file=file, color=color)73+ echo(self.ctx.get_usage() + "\n%s" % hint, file=file, color=color)74+ echo("Error: %s" % self.format_message(), file=file, color=color)75 76 77 class BadParameter(UsageError):78 """An exception that formats out a standardized error message for a12 unmodified lines91 a string it's used as such, if it's a list then92 each item is quoted and separated.93 """94 93- def __init__(self, message, ctx=None, param=None,94- param_hint=None):95+ def __init__(self, message, ctx=None, param=None, param_hint=None):96 UsageError.__init__(self, message, ctx)97 self.param = param98 self.param_hint = param_hint99 2 unmodified lines102 param_hint = self.param_hint103 elif self.param is not None:104 param_hint = self.param.get_error_hint(self.ctx)105 else:105- return 'Invalid value: %s' % self.message106+ return "Invalid value: %s" % self.message107 param_hint = _join_param_hints(param_hint)108 108- return 'Invalid value for %s: %s' % (param_hint, self.message)109+ return "Invalid value for %s: %s" % (param_hint, self.message)110 111 112 class MissingParameter(BadParameter):113 """Raised if click required an option or argument but it was not6 unmodified lines120 the given `param`. Valid values are ``'parameter'``,121 ``'option'`` or ``'argument'``.122 """123 123- def __init__(self, message=None, ctx=None, param=None,124- param_hint=None, param_type=None):124+ def __init__(125+ self, message=None, ctx=None, param=None, param_hint=None, param_type=None126+ ):127 BadParameter.__init__(self, message, ctx, param, param_hint)128 self.param_type = param_type129 130 def format_message(self):13 unmodified lines144 if self.param is not None:145 msg_extra = self.param.type.get_missing_message(self.param)146 if msg_extra:147 if msg:146- msg += '. ' + msg_extra148+ msg += ". " + msg_extra149 else:150 msg = msg_extra151 150- return 'Missing %s%s%s%s' % (152+ return "Missing %s%s%s%s" % (153 param_type,152- param_hint and ' %s' % param_hint or '',153- msg and '. ' or '.',154- msg or '',154+ param_hint and " %s" % param_hint or "",155+ msg and ". " or ".",156+ msg or "",157 )158 159 def __str__(self):160 if self.message is None:15 unmodified lines176 177 .. versionadded:: 4.0178 """179 178- def __init__(self, option_name, message=None, possibilities=None,179- ctx=None):180+ def __init__(self, option_name, message=None, possibilities=None, ctx=None):181 if message is None:181- message = 'no such option: %s' % option_name182+ message = "no such option: %s" % option_name183 UsageError.__init__(self, message, ctx)184 self.option_name = option_name185 self.possibilities = possibilities186 187 def format_message(self):188 bits = [self.message]189 if self.possibilities:190 if len(self.possibilities) == 1:190- bits.append('Did you mean %s?' % self.possibilities[0])191+ bits.append("Did you mean %s?" % self.possibilities[0])192 else:193 possibilities = sorted(self.possibilities)193- bits.append('(Possible options: %s)' % ', '.join(possibilities))194- return ' '.join(bits)194+ bits.append("(Possible options: %s)" % ", ".join(possibilities))195+ return " ".join(bits)196 197 198 class BadOptionUsage(UsageError):199 """Raised if an option is generally supplied but the use of the option27 unmodified lines227 228 def __init__(self, filename, hint=None):229 ui_filename = filename_to_ui(filename)230 if hint is None:230- hint = 'unknown error'231+ hint = "unknown error"232 ClickException.__init__(self, hint)233 self.ui_filename = ui_filename234 self.filename = filename235 236 def format_message(self):236- return 'Could not open file %s: %s' % (self.ui_filename, self.message)237+ return "Could not open file %s: %s" % (self.ui_filename, self.message)238 239 240 class Abort(RuntimeError):241 """An internal signalling exception that signals Click to abort."""4 unmodified lines246 status code.247 248 :param code: the status code to exit with.249 """250+251 def __init__(self, code=0):252 self.exit_code = codemodified:src/click/formatting.py+60 added-43 removed
17 unmodified lines18 19 def iter_rows(rows, col_count):20 for row in rows:21 row = tuple(row)22- yield row + ('',) * (col_count - len(row))22+ yield row + ("",) * (col_count - len(row))23 24 25-def wrap_text(text, width=78, initial_indent='', subsequent_indent='',26- preserve_paragraphs=False):25+def wrap_text(26+ text, width=78, initial_indent="", subsequent_indent="", preserve_paragraphs=False27+):28 """A helper function that intelligently wraps text. By default, it29 assumes that it operates on a single paragraph of text but if the30 `preserve_paragraphs` parameter is provided it will intelligently31 handle paragraphs (defined by two empty lines).11 unmodified lines43 :param preserve_paragraphs: if this flag is set then the wrapping will44 intelligently handle paragraphs.45 """46 from ._textwrap import TextWrapper47+48 text = text.expandtabs()49+ wrapper = TextWrapper(50+ width,47- wrapper = TextWrapper(width, initial_indent=initial_indent,48- subsequent_indent=subsequent_indent,49- replace_whitespace=False)51+ initial_indent=initial_indent,52+ subsequent_indent=subsequent_indent,53+ replace_whitespace=False,54+ )55 if not preserve_paragraphs:56 return wrapper.fill(text)57 58 p = []2 unmodified lines61 62 def _flush_par():63 if not buf:64 return60- if buf[0].strip() == '\b':61- p.append((indent or 0, True, '\n'.join(buf[1:])))65+ if buf[0].strip() == "\b":66+ p.append((indent or 0, True, "\n".join(buf[1:])))67 else:63- p.append((indent or 0, False, ' '.join(buf)))68+ p.append((indent or 0, False, " ".join(buf)))69 del buf[:]70 71 for line in text.splitlines():72 if not line:8 unmodified lines81 _flush_par()82 83 rv = []84 for indent, raw, text in p:80- with wrapper.extra_indent(' ' * indent):85+ with wrapper.extra_indent(" " * indent):86 if raw:87 rv.append(wrapper.indent_only(text))88 else:89 rv.append(wrapper.fill(text))90 86- return '\n\n'.join(rv)91+ return "\n\n".join(rv)92 93 94 class HelpFormatter(object):95 """This class helps with formatting text-based help pages. It's30 unmodified lines126 def dedent(self):127 """Decreases the indentation."""128 self.current_indent -= self.indent_increment129 125- def write_usage(self, prog, args='', prefix='Usage: '):130+ def write_usage(self, prog, args="", prefix="Usage: "):131 """Writes a usage line into the buffer.132 133 :param prog: the program name.134 :param args: whitespace separated list of arguments.135 :param prefix: the prefix for the first line.136 """132- usage_prefix = '%*s%s ' % (self.current_indent, prefix, prog)137+ usage_prefix = "%*s%s " % (self.current_indent, prefix, prog)138 text_width = self.width - self.current_indent139 140 if text_width >= (term_len(usage_prefix) + 20):141 # The arguments will fit to the right of the prefix.137- indent = ' ' * term_len(usage_prefix)138- self.write(wrap_text(args, text_width,139- initial_indent=usage_prefix,140- subsequent_indent=indent))142+ indent = " " * term_len(usage_prefix)143+ self.write(144+ wrap_text(145+ args,146+ text_width,147+ initial_indent=usage_prefix,148+ subsequent_indent=indent,149+ )150+ )151 else:152 # The prefix is too long, put the arguments on the next line.153 self.write(usage_prefix)144- self.write('\n')145- indent = ' ' * (max(self.current_indent, term_len(prefix)) + 4)146- self.write(wrap_text(args, text_width,147- initial_indent=indent,148- subsequent_indent=indent))154+ self.write("\n")155+ indent = " " * (max(self.current_indent, term_len(prefix)) + 4)156+ self.write(157+ wrap_text(158+ args, text_width, initial_indent=indent, subsequent_indent=indent159+ )160+ )161 150- self.write('\n')162+ self.write("\n")163 164 def write_heading(self, heading):165 """Writes a heading into the buffer."""154- self.write('%*s%s:\n' % (self.current_indent, '', heading))166+ self.write("%*s%s:\n" % (self.current_indent, "", heading))167 168 def write_paragraph(self):169 """Writes a paragraph into the buffer."""170 if self.buffer:159- self.write('\n')171+ self.write("\n")172 173 def write_text(self, text):174 """Writes re-indented text into the buffer. This rewraps and175 preserves paragraphs.176 """177 text_width = max(self.width - self.current_indent, 11)166- indent = ' ' * self.current_indent167- self.write(wrap_text(text, text_width,168- initial_indent=indent,169- subsequent_indent=indent,170- preserve_paragraphs=True))171- self.write('\n')178+ indent = " " * self.current_indent179+ self.write(180+ wrap_text(181+ text,182+ text_width,183+ initial_indent=indent,184+ subsequent_indent=indent,185+ preserve_paragraphs=True,186+ )187+ )188+ self.write("\n")189 190 def write_dl(self, rows, col_max=30, col_spacing=2):191 """Writes a definition list into the buffer. This is how options192 and commands are usually formatted.5 unmodified lines198 """199 rows = list(rows)200 widths = measure_table(rows)201 if len(widths) != 2:185- raise TypeError('Expected two columns for definition list')202+ raise TypeError("Expected two columns for definition list")203 204 first_col = min(widths[0], col_max) + col_spacing205 206 for first, second in iter_rows(rows, len(widths)):190- self.write('%*s%s' % (self.current_indent, '', first))207+ self.write("%*s%s" % (self.current_indent, "", first))208 if not second:192- self.write('\n')209+ self.write("\n")210 continue211 if term_len(first) <= first_col - col_spacing:195- self.write(' ' * (first_col - term_len(first)))212+ self.write(" " * (first_col - term_len(first)))213 else:197- self.write('\n')198- self.write(' ' * (first_col + self.current_indent))214+ self.write("\n")215+ self.write(" " * (first_col + self.current_indent))216 217 text_width = max(self.width - first_col - 2, 10)218 wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)219 lines = wrapped_text.splitlines()220 221 if lines:205- self.write(lines[0] + '\n')222+ self.write(lines[0] + "\n")223 224 for line in lines[1:]:208- self.write('%*s%s\n' % (first_col + self.current_indent, '', line))225+ self.write("%*s%s\n" % (first_col + self.current_indent, "", line))226 227 if len(lines) > 1:228 # separate long help from next option229 self.write("\n")230 else:214- self.write('\n')231+ self.write("\n")232 233 @contextmanager234 def section(self, name):235 """Helpful context manager that writes a paragraph, a heading,19 unmodified lines255 self.dedent()256 257 def getvalue(self):258 """Returns the buffer contents."""242- return ''.join(self.buffer)259+ return "".join(self.buffer)260 261 262 def join_options(options):263 """Given a list of option strings this joins them in the most appropriate4 unmodified lines268 rv = []269 any_prefix_is_slash = False270 for opt in options:271 prefix = split_opt(opt)[0]255- if prefix == '/':272+ if prefix == "/":273 any_prefix_is_slash = True274 rv.append((len(prefix), opt))275 276 rv.sort(key=lambda x: x[0])277 261- rv = ', '.join(x[1] for x in rv)278+ rv = ", ".join(x[1] for x in rv)279 return rv, any_prefix_is_slashmodified:src/click/globals.py+3 added-3 removed
17 unmodified lines18 is available. The default behavior is to raise a19 :exc:`RuntimeError`.20 """21 try:22- return getattr(_local, 'stack')[-1]22+ return getattr(_local, "stack")[-1]23 except (AttributeError, IndexError):24 if not silent:25- raise RuntimeError('There is no active click context.')25+ raise RuntimeError("There is no active click context.")26 27 28 def push_context(ctx):29 """Pushes a new context to the current stack."""30- _local.__dict__.setdefault('stack', []).append(ctx)30+ _local.__dict__.setdefault("stack", []).append(ctx)31 32 33 def pop_context():34 """Removes the top level from the stack."""13 unmodified linesmodified:src/click/parser.py+36 added-40 removed
62 unmodified lines63 x.reverse()64 rv.append(tuple(x))65 elif nargs < 0:66 if spos is not None:67- raise TypeError('Cannot have two nargs < 0')67+ raise TypeError("Cannot have two nargs < 0")68 spos = len(rv)69 rv.append(None)70 71 # spos is the position of the wildcard (star). If it's not `None`,72 # we fill it with the remainder.73 if spos is not None:74 rv[spos] = tuple(args)75 args = []76- rv[spos + 1:] = reversed(rv[spos + 1:])76+ rv[spos + 1 :] = reversed(rv[spos + 1 :])77 78 return tuple(rv), list(args)79 80 81 def _error_opt_args(nargs, opt):82 if nargs == 1:83- raise BadOptionUsage(opt, '%s option requires an argument' % opt)84- raise BadOptionUsage(opt, '%s option requires %d arguments' % (opt, nargs))83+ raise BadOptionUsage(opt, "%s option requires an argument" % opt)84+ raise BadOptionUsage(opt, "%s option requires %d arguments" % (opt, nargs))85 86 87 def split_opt(opt):88 first = opt[:1]89 if first.isalnum():90- return '', opt90+ return "", opt91 if opt[1:2] == first:92 return opt[:2], opt[2:]93 return first, opt[1:]94 7 unmodified lines102 103 def split_arg_string(string):104 """Given an argument string this attempts to split it into small parts."""105 rv = []106- for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"107- r'|"([^"\\]*(?:\\.[^"\\]*)*)"'108- r'|\S+)\s*', string, re.S):106+ for match in re.finditer(107+ r"('([^'\\]*(?:\\.[^'\\]*)*)'|\"([^\"\\]*(?:\\.[^\"\\]*)*)\"|\S+)\s*",108+ string,109+ re.S,110+ ):111 arg = match.group().strip()110- if arg[:1] == arg[-1:] and arg[:1] in '"\'':111- arg = arg[1:-1].encode('ascii', 'backslashreplace') \112- .decode('unicode-escape')112+ if arg[:1] == arg[-1:] and arg[:1] in "\"'":113+ arg = arg[1:-1].encode("ascii", "backslashreplace").decode("unicode-escape")114 try:115 arg = type(string)(arg)116 except UnicodeError:117 pass1 unmodified line119 return rv120 121 122 class Option(object):122-123 def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):124 self._short_opts = []125 self._long_opts = []126 self.prefixes = set()127 128 for opt in opts:129 prefix, value = split_opt(opt)130 if not prefix:131- raise ValueError('Invalid start character for option (%s)'132- % opt)131+ raise ValueError("Invalid start character for option (%s)" % opt)132 self.prefixes.add(prefix[0])133 if len(prefix) == 1 and len(value) == 1:134 self._short_opts.append(opt)135 else:136 self._long_opts.append(opt)137 self.prefixes.add(prefix)138 139 if action is None:141- action = 'store'140+ action = "store"141 142 self.dest = dest143 self.action = action144 self.nargs = nargs1 unmodified line146 self.obj = obj147 148 @property149 def takes_value(self):151- return self.action in ('store', 'append')150+ return self.action in ("store", "append")151 152 def process(self, value, state):154- if self.action == 'store':153+ if self.action == "store":154 state.opts[self.dest] = value156- elif self.action == 'store_const':155+ elif self.action == "store_const":156 state.opts[self.dest] = self.const158- elif self.action == 'append':157+ elif self.action == "append":158 state.opts.setdefault(self.dest, []).append(value)160- elif self.action == 'append_const':159+ elif self.action == "append_const":160 state.opts.setdefault(self.dest, []).append(self.const)162- elif self.action == 'count':161+ elif self.action == "count":162 state.opts[self.dest] = state.opts.get(self.dest, 0) + 1163 else:165- raise ValueError('unknown action %r' % self.action)164+ raise ValueError("unknown action %r" % self.action)165 state.order.append(self.obj)166 167 168 class Argument(object):170-169 def __init__(self, dest, nargs=1, obj=None):170 self.dest = dest171 self.nargs = nargs172 self.obj = obj3 unmodified lines176 holes = sum(1 for x in value if x is None)177 if holes == len(value):178 value = None179 elif holes != 0:182- raise BadArgumentUsage('argument %s takes %d values'183- % (self.dest, self.nargs))180+ raise BadArgumentUsage(181+ "argument %s takes %d values" % (self.dest, self.nargs)182+ )183 state.opts[self.dest] = value184 state.order.append(self.obj)185 186 187 class ParsingState(object):189-188 def __init__(self, rargs):189 self.opts = {}190 self.largs = []191 self.rargs = rargs32 unmodified lines224 self.allow_interspersed_args = ctx.allow_interspersed_args225 self.ignore_unknown_options = ctx.ignore_unknown_options226 self._short_opt = {}227 self._long_opt = {}230- self._opt_prefixes = set(['-', '--'])228+ self._opt_prefixes = set(["-", "--"])229 self._args = []230 233- def add_option(self, opts, dest, action=None, nargs=1, const=None,234- obj=None):231+ def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None):232 """Adds a new option named `dest` to the parser. The destination233 is not inferred (unlike with optparse) and needs to be explicitly234 provided. Action can be any of ``store``, ``store_const``,235 ``append``, ``appnd_const`` or ``count``.3 unmodified lines239 """240 if obj is None:241 obj = dest242 opts = [normalize_opt(opt, self.ctx) for opt in opts]246- option = Option(opts, dest, action=action, nargs=nargs,247- const=const, obj=obj)243+ option = Option(opts, dest, action=action, nargs=nargs, const=const, obj=obj)244 self._opt_prefixes.update(option.prefixes)245 for opt in option._short_opts:246 self._short_opt[opt] = option247 for opt in option._long_opts:25 unmodified lines273 raise274 return state.opts, state.largs, state.order275 276 def _process_args_for_args(self, state):281- pargs, args = _unpack_args(state.largs + state.rargs,282- [x.nargs for x in self._args])277+ pargs, args = _unpack_args(278+ state.largs + state.rargs, [x.nargs for x in self._args]279+ )280 281 for idx, arg in enumerate(self._args):282 arg.process(pargs[idx], state)283 5 unmodified lines289 arg = state.rargs.pop(0)290 arglen = len(arg)291 # Double dashes always handled explicitly regardless of what292 # prefixes are valid.296- if arg == '--':293+ if arg == "--":294 return295 elif arg[:1] in self._opt_prefixes and arglen > 1:296 self._process_opts(arg, state)297 elif self.allow_interspersed_args:23 unmodified lines321 # not a very interesting subset!322 323 def _match_long_opt(self, opt, explicit_value, state):324 if opt not in self._long_opt:328- possibilities = [word for word in self._long_opt329- if word.startswith(opt)]325+ possibilities = [word for word in self._long_opt if word.startswith(opt)]326 raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)327 328 option = self._long_opt[opt]329 if option.takes_value:13 unmodified lines343 value = tuple(state.rargs[:nargs])344 del state.rargs[:nargs]345 346 elif explicit_value is not None:351- raise BadOptionUsage(opt, '%s option does not take a value' % opt)347+ raise BadOptionUsage(opt, "%s option does not take a value" % opt)348 349 else:350 value = None351 43 unmodified lines395 # remaining options and re-attach the prefix, then report that396 # to the state as new larg. This way there is basic combinatorics397 # that can be achieved while still ignoring unknown arguments.398 if self.ignore_unknown_options and unknown_options:403- state.largs.append(prefix + ''.join(unknown_options))399+ state.largs.append(prefix + "".join(unknown_options))400 401 def _process_opts(self, arg, state):402 explicit_value = None403 # Long option handling happens in two parts. The first part is404 # supporting explicitly attached values. In any case, we will try405 # to long match the option first.410- if '=' in arg:411- long_opt, explicit_value = arg.split('=', 1)406+ if "=" in arg:407+ long_opt, explicit_value = arg.split("=", 1)408 else:409 long_opt = arg410 norm_long_opt = normalize_opt(long_opt, self.ctx)411 17 unmodified linesmodified:src/click/termui.py+127 added-75 removed
25 unmodified lines26 # functions to customize how they work.27 visible_prompt_func = raw_input28 29 _ansi_colors = {30- 'black': 30,31- 'red': 31,32- 'green': 32,33- 'yellow': 33,34- 'blue': 34,35- 'magenta': 35,36- 'cyan': 36,37- 'white': 37,38- 'reset': 39,39- 'bright_black': 90,40- 'bright_red': 91,41- 'bright_green': 92,42- 'bright_yellow': 93,43- 'bright_blue': 94,44- 'bright_magenta': 95,45- 'bright_cyan': 96,46- 'bright_white': 97,30+ "black": 30,31+ "red": 31,32+ "green": 32,33+ "yellow": 33,34+ "blue": 34,35+ "magenta": 35,36+ "cyan": 36,37+ "white": 37,38+ "reset": 39,39+ "bright_black": 90,40+ "bright_red": 91,41+ "bright_green": 92,42+ "bright_yellow": 93,43+ "bright_blue": 94,44+ "bright_magenta": 95,45+ "bright_cyan": 96,46+ "bright_white": 97,47 }48-_ansi_reset_all = '\033[0m'48+_ansi_reset_all = "\033[0m"49 50 51 def hidden_prompt_func(prompt):52 import getpass53+54 return getpass.getpass(prompt)55 56 56-def _build_prompt(text, suffix, show_default=False, default=None, show_choices=True, type=None):57+def _build_prompt(58+ text, suffix, show_default=False, default=None, show_choices=True, type=None59+):60 prompt = text61 if type is not None and show_choices and isinstance(type, Choice):59- prompt += ' (' + ", ".join(map(str, type.choices)) + ')'62+ prompt += " (" + ", ".join(map(str, type.choices)) + ")"63 if default is not None and show_default:61- prompt = '%s [%s]' % (prompt, _format_default(default))64+ prompt = "%s [%s]" % (prompt, _format_default(default))65 return prompt + suffix66 67 68 def _format_default(default):2 unmodified lines71 72 return default73 74 72-def prompt(text, default=None, hide_input=False, confirmation_prompt=False,73- type=None, value_proc=None, prompt_suffix=': ', show_default=True,74- err=False, show_choices=True):75+def prompt(76+ text,77+ default=None,78+ hide_input=False,79+ confirmation_prompt=False,80+ type=None,81+ value_proc=None,82+ prompt_suffix=": ",83+ show_default=True,84+ err=False,85+ show_choices=True,86+):87 """Prompts a user for input. This is a convenience function that can88 be used to prompt a user for input later.89 90 If the user aborts the input by sending a interrupt signal, this34 unmodified lines125 try:126 # Write the prompt separately so that we get nice127 # coloring through colorama on Windows128 echo(text, nl=False, err=err)117- return f('')129+ return f("")130 except (KeyboardInterrupt, EOFError):131 # getpass doesn't print a newline if the user aborts input with ^C.132 # Allegedly this behavior is inherited from getpass(3).133 # A doc bug has been filed at https://bugs.python.org/issue247113 unmodified lines137 138 if value_proc is None:139 value_proc = convert_type(type, default)140 129- prompt = _build_prompt(text, prompt_suffix, show_default, default, show_choices, type)141+ prompt = _build_prompt(142+ text, prompt_suffix, show_default, default, show_choices, type143+ )144 145 while 1:146 while 1:147 value = prompt_func(prompt)7 unmodified lines155 return default156 try:157 result = value_proc(value)158 except UsageError as e:145- echo('Error: %s' % e.message, err=err)159+ echo("Error: %s" % e.message, err=err)160 continue161 if not confirmation_prompt:162 return result163 while 1:150- value2 = prompt_func('Repeat for confirmation: ')164+ value2 = prompt_func("Repeat for confirmation: ")165 if value2:166 break167 if value == value2:168 return result155- echo('Error: the two entered values do not match', err=err)169+ echo("Error: the two entered values do not match", err=err)170 171 158-def confirm(text, default=False, abort=False, prompt_suffix=': ',159- show_default=True, err=False):172+def confirm(173+ text, default=False, abort=False, prompt_suffix=": ", show_default=True, err=False174+):175 """Prompts for confirmation (yes/no question).176 177 If the user aborts the input by sending a interrupt signal this178 function will catch it and raise a :exc:`Abort` exception.9 unmodified lines188 :param show_default: shows or hides the default value in the prompt.189 :param err: if set to true the file defaults to ``stderr`` instead of190 ``stdout``, the same as with echo.191 """177- prompt = _build_prompt(text, prompt_suffix, show_default,178- default and 'Y/n' or 'y/N')192+ prompt = _build_prompt(193+ text, prompt_suffix, show_default, default and "Y/n" or "y/N"194+ )195 while 1:196 try:197 # Write the prompt separately so that we get nice198 # coloring through colorama on Windows199 echo(prompt, nl=False, err=err)184- value = visible_prompt_func('').lower().strip()200+ value = visible_prompt_func("").lower().strip()201 except (KeyboardInterrupt, EOFError):202 raise Abort()187- if value in ('y', 'yes'):203+ if value in ("y", "yes"):204 rv = True189- elif value in ('n', 'no'):205+ elif value in ("n", "no"):206 rv = False191- elif value == '':207+ elif value == "":208 rv = default209 else:194- echo('Error: invalid input', err=err)210+ echo("Error: invalid input", err=err)211 continue212 break213 if abort and not rv:214 raise Abort()6 unmodified lines221 """222 # If shutil has get_terminal_size() (Python 3.3 and later) use that223 if sys.version_info >= (3, 3):224 import shutil225+209- shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None)226+ shutil_get_terminal_size = getattr(shutil, "get_terminal_size", None)227 if shutil_get_terminal_size:228 sz = shutil_get_terminal_size()229 return sz.columns, sz.lines230 9 unmodified lines240 def ioctl_gwinsz(fd):241 try:242 import fcntl243 import termios227- cr = struct.unpack(228- 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))244+245+ cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))246 except Exception:247 return248 return cr249 7 unmodified lines257 os.close(fd)258 except Exception:259 pass260 if not cr or not cr[0] or not cr[1]:244- cr = (os.environ.get('LINES', 25),245- os.environ.get('COLUMNS', DEFAULT_COLUMNS))261+ cr = (os.environ.get("LINES", 25), os.environ.get("COLUMNS", DEFAULT_COLUMNS))262 return int(cr[1]), int(cr[0])263 264 265 def echo_via_pager(text_or_generator, color=None):17 unmodified lines283 else:284 i = iter(text_or_generator)285 286 # convert every element of i to a text type if necessary271- text_generator = (el if isinstance(el, string_types) else text_type(el)272- for el in i)287+ text_generator = (el if isinstance(el, string_types) else text_type(el) for el in i)288 289 from ._termui_impl import pager290+291 return pager(itertools.chain(text_generator, "\n"), color)292 293 278-def progressbar(iterable=None, length=None, label=None, show_eta=True,279- show_percent=None, show_pos=False,280- item_show_func=None, fill_char='#', empty_char='-',281- bar_template='%(label)s [%(bar)s] %(info)s',282- info_sep=' ', width=36, file=None, color=None):294+def progressbar(295+ iterable=None,296+ length=None,297+ label=None,298+ show_eta=True,299+ show_percent=None,300+ show_pos=False,301+ item_show_func=None,302+ fill_char="#",303+ empty_char="-",304+ bar_template="%(label)s [%(bar)s] %(info)s",305+ info_sep=" ",306+ width=36,307+ file=None,308+ color=None,309+):310 """This function creates an iterable context manager that can be used311 to iterate over something while showing a progress bar. It will312 either iterate over the `iterable` or `length` items (that are counted313 up). While iteration happens, this function will print a rendered77 unmodified lines391 codes are included anywhere in the progress bar output392 which is not the case by default.393 """394 from ._termui_impl import ProgressBar395+396 color = resolve_color_default(color)369- return ProgressBar(iterable=iterable, length=length, show_eta=show_eta,370- show_percent=show_percent, show_pos=show_pos,371- item_show_func=item_show_func, fill_char=fill_char,372- empty_char=empty_char, bar_template=bar_template,373- info_sep=info_sep, file=file, label=label,374- width=width, color=color)397+ return ProgressBar(398+ iterable=iterable,399+ length=length,400+ show_eta=show_eta,401+ show_percent=show_percent,402+ show_pos=show_pos,403+ item_show_func=item_show_func,404+ fill_char=fill_char,405+ empty_char=empty_char,406+ bar_template=bar_template,407+ info_sep=info_sep,408+ file=file,409+ label=label,410+ width=width,411+ color=color,412+ )413 414 415 def clear():416 """Clears the terminal screen. This will have the effect of clearing7 unmodified lines424 # If we're on Windows and we don't have colorama available, then we425 # clear the screen by shelling out. Otherwise we can use an escape426 # sequence.427 if WIN:390- os.system('cls')428+ os.system("cls")429 else:392- sys.stdout.write('\033[2J\033[1;1H')430+ sys.stdout.write("\033[2J\033[1;1H")431 432 395-def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,396- blink=None, reverse=None, reset=True):433+def style(434+ text,435+ fg=None,436+ bg=None,437+ bold=None,438+ dim=None,439+ underline=None,440+ blink=None,441+ reverse=None,442+ reset=True,443+):444 """Styles a text with ANSI styles and returns the new string. By445 default the styling is self contained which means that at the end446 of the string a reset code is issued. This can be prevented by447 passing ``reset=False``.46 unmodified lines494 """495 bits = []496 if fg:497 try:451- bits.append('\033[%dm' % (_ansi_colors[fg]))498+ bits.append("\033[%dm" % (_ansi_colors[fg]))499 except KeyError:453- raise TypeError('Unknown color %r' % fg)500+ raise TypeError("Unknown color %r" % fg)501 if bg:502 try:456- bits.append('\033[%dm' % (_ansi_colors[bg] + 10))503+ bits.append("\033[%dm" % (_ansi_colors[bg] + 10))504 except KeyError:458- raise TypeError('Unknown color %r' % bg)505+ raise TypeError("Unknown color %r" % bg)506 if bold is not None:460- bits.append('\033[%dm' % (1 if bold else 22))507+ bits.append("\033[%dm" % (1 if bold else 22))508 if dim is not None:462- bits.append('\033[%dm' % (2 if dim else 22))509+ bits.append("\033[%dm" % (2 if dim else 22))510 if underline is not None:464- bits.append('\033[%dm' % (4 if underline else 24))511+ bits.append("\033[%dm" % (4 if underline else 24))512 if blink is not None:466- bits.append('\033[%dm' % (5 if blink else 25))513+ bits.append("\033[%dm" % (5 if blink else 25))514 if reverse is not None:468- bits.append('\033[%dm' % (7 if reverse else 27))515+ bits.append("\033[%dm" % (7 if reverse else 27))516 bits.append(text)517 if reset:518 bits.append(_ansi_reset_all)472- return ''.join(bits)519+ return "".join(bits)520 521 522 def unstyle(text):523 """Removes ANSI styling information from a string. Usually it's not23 unmodified lines547 message = style(message, **styles)548 return echo(message, file=file, nl=nl, err=err, color=color)549 550 504-def edit(text=None, editor=None, env=None, require_save=True,505- extension='.txt', filename=None):551+def edit(552+ text=None, editor=None, env=None, require_save=True, extension=".txt", filename=None553+):554 r"""Edits the given text in the defined editor. If an editor is given555 (should be the full path to the executable but the regular operating556 system search path is used for finding the executable) it overrides557 the detected editor. Optionally, some environment variables can be20 unmodified lines578 provided text contents. It will not use a temporary579 file as an indirection in that case.580 """581 from ._termui_impl import Editor534- editor = Editor(editor=editor, env=env, require_save=require_save,535- extension=extension)582+583+ editor = Editor(584+ editor=editor, env=env, require_save=require_save, extension=extension585+ )586 if filename is None:587 return editor.edit(text)588 editor.edit_file(filename)589 20 unmodified lines610 might have weird effects if the URL does not point to611 the filesystem.612 """613 from ._termui_impl import open_url614+615 return open_url(url, wait=wait, locate=locate)616 617 618 # If this is provided, getchar() calls into this instead. This is used28 unmodified lines647 648 649 def raw_terminal():650 from ._termui_impl import raw_terminal as f651+652 return f()653 654 603-def pause(info='Press any key to continue ...', err=False):655+def pause(info="Press any key to continue ...", err=False):656 """This command stops execution and waits for the user to press any657 key to continue. This is similar to the Windows batch "pause"658 command. If the program is not run through a terminal, this command659 will instead do nothing.22 unmodified linesmodified:src/click/testing.py+44 added-36 removed
11 unmodified lines12 # If someone wants to vendor click, we want to ensure the13 # correct package is discovered. Ideally we could use a14 # relative import here but unfortunately Python does not15 # support that.16-clickpkg = sys.modules[__name__.rsplit('.', 1)[0]]16+clickpkg = sys.modules[__name__.rsplit(".", 1)[0]]17 18 19 if PY2:20 from cStringIO import StringIO2 unmodified lines23 from ._compat import _find_binary_reader24 25 26 class EchoingStdin(object):27-27 def __init__(self, input, output):28 self._input = input29 self._output = output30 21 unmodified lines52 53 54 def make_input_stream(input, charset):55 # Is already an input stream.57- if hasattr(input, 'read'):56+ if hasattr(input, "read"):57 if PY2:58 return input59 rv = _find_binary_reader(input)60 if rv is not None:61 return rv63- raise TypeError('Could not find binary reader for input stream.')62+ raise TypeError("Could not find binary reader for input stream.")63 64 if input is None:66- input = b''65+ input = b""66 elif not isinstance(input, bytes):67 input = input.encode(charset)68 if PY2:69 return StringIO(input)2 unmodified lines72 73 class Result(object):74 """Holds the captured result of an invoked CLI script."""75 77- def __init__(self, runner, stdout_bytes, stderr_bytes, exit_code,78- exception, exc_info=None):76+ def __init__(77+ self, runner, stdout_bytes, stderr_bytes, exit_code, exception, exc_info=None78+ ):79 #: The runner that created the result80 self.runner = runner81 #: The standard output as bytes.82 self.stdout_bytes = stdout_bytes13 unmodified lines96 97 @property98 def stdout(self):99 """The standard output as unicode string."""100- return self.stdout_bytes.decode(self.runner.charset, 'replace') \101- .replace('\r\n', '\n')100+ return self.stdout_bytes.decode(self.runner.charset, "replace").replace(101+ "\r\n", "\n"102+ )103 104 @property105 def stderr(self):106 """The standard error as unicode string."""107 if self.stderr_bytes is None:108 raise ValueError("stderr not separately captured")108- return self.stderr_bytes.decode(self.runner.charset, 'replace') \109- .replace('\r\n', '\n')109+ return self.stderr_bytes.decode(self.runner.charset, "replace").replace(110+ "\r\n", "\n"111+ )112 111-113 def __repr__(self):113- return '<%s %s>' % (114+ return "<%s %s>" % (115 type(self).__name__,115- self.exception and repr(self.exception) or 'okay',116+ self.exception and repr(self.exception) or "okay",117 )118 119 120 class CliRunner(object):16 unmodified lines137 noisy stderr, such that each may be measured138 independently139 """140 140- def __init__(self, charset=None, env=None, echo_stdin=False,141- mix_stderr=True):141+ def __init__(self, charset=None, env=None, echo_stdin=False, mix_stderr=True):142 if charset is None:143- charset = 'utf-8'143+ charset = "utf-8"144 self.charset = charset145 self.env = env or {}146 self.echo_stdin = echo_stdin147 self.mix_stderr = mix_stderr2 unmodified lines150 """Given a command object it will return the default program name151 for it. The default is the `name` attribute or ``"root"`` if not152 set.153 """154- return cli.name or 'root'154+ return cli.name or "root"155 156 def make_env(self, overrides=None):157 """Returns the environment overrides for invoking a script."""158 rv = dict(self.env)41 unmodified lines200 bytes_output = io.BytesIO()201 if self.echo_stdin:202 input = EchoingStdin(input, bytes_output)203 input = io.TextIOWrapper(input, encoding=self.charset)204- sys.stdout = io.TextIOWrapper(205- bytes_output, encoding=self.charset)204+ sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)205 if not self.mix_stderr:206 bytes_error = io.BytesIO()208- sys.stderr = io.TextIOWrapper(209- bytes_error, encoding=self.charset)207+ sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)208 209 if self.mix_stderr:210 sys.stderr = sys.stdout211 212 sys.stdin = input213 214 def visible_input(prompt=None):217- sys.stdout.write(prompt or '')218- val = input.readline().rstrip('\r\n')219- sys.stdout.write(val + '\n')215+ sys.stdout.write(prompt or "")216+ val = input.readline().rstrip("\r\n")217+ sys.stdout.write(val + "\n")218 sys.stdout.flush()219 return val220 221 def hidden_input(prompt=None):224- sys.stdout.write((prompt or '') + '\n')222+ sys.stdout.write((prompt or "") + "\n")223 sys.stdout.flush()226- return input.readline().rstrip('\r\n')224+ return input.readline().rstrip("\r\n")225 226 def _getchar(echo):227 char = sys.stdin.read(1)228 if echo:46 unmodified lines275 clickpkg.termui._getchar = old__getchar_func276 clickpkg.utils.should_strip_ansi = old_should_strip_ansi277 clickpkg.formatting.FORCED_WIDTH = old_forced_width278 281- def invoke(self, cli, args=None, input=None, env=None,282- catch_exceptions=True, color=False, **extra):279+ def invoke(280+ self,281+ cli,282+ args=None,283+ input=None,284+ env=None,285+ catch_exceptions=True,286+ color=False,287+ **extra288+ ):289 """Invokes a command in an isolated environment. The arguments are290 forwarded directly to the command line script, the `extra` keyword291 arguments are passed to the :meth:`~clickpkg.Command.main` function of292 the command.48 unmodified lines341 exception = e342 343 if not isinstance(exit_code, int):344 sys.stdout.write(str(exit_code))339- sys.stdout.write('\n')345+ sys.stdout.write("\n")346 exit_code = 1347 348 except Exception as e:349 if not catch_exceptions:8 unmodified lines358 stderr = None359 else:360 stderr = outstreams[1].getvalue()361 362+ return Result(356- return Result(runner=self,357- stdout_bytes=stdout,358- stderr_bytes=stderr,359- exit_code=exit_code,360- exception=exception,361- exc_info=exc_info)363+ runner=self,364+ stdout_bytes=stdout,365+ stderr_bytes=stderr,366+ exit_code=exit_code,367+ exception=exception,368+ exc_info=exc_info,369+ )370 371 @contextlib.contextmanager372 def isolated_filesystem(self):373 """A context manager that creates a temporary folder and changes13 unmodified linesmodified:src/click/types.py+168 added-110 removed
25 unmodified lines26 * it needs to be able to deal with param and context being `None`.27 This can be the case when the object is used with prompt28 inputs.29 """30+31 is_composite = False32 33 #: the descriptive name of this type34 name = None33 unmodified lines68 If the splitter is set to `None`, which means that whitespace splits,69 then leading and trailing whitespace is ignored. Otherwise, leading70 and trailing splitters usually lead to empty items being included.71 """71- return (rv or '').split(self.envvar_list_splitter)72+ return (rv or "").split(self.envvar_list_splitter)73 74 def fail(self, message, param=None, ctx=None):75 """Helper method to fail with an invalid value message."""76 raise BadParameter(message, ctx=ctx, param=param)7 unmodified lines84 raise NotImplementedError()85 86 87 class FuncParamType(ParamType):87-88 def __init__(self, func):89 self.name = func.__name__90 self.func = func91 3 unmodified lines95 except ValueError:96 try:97 value = text_type(value)98 except UnicodeError:99- value = str(value).decode('utf-8', 'replace')99+ value = str(value).decode("utf-8", "replace")100 self.fail(value, param, ctx)101 102 103 class UnprocessedParamType(ParamType):104- name = 'text'104+ name = "text"105 106 def convert(self, value, param, ctx):107 return value108 109 def __repr__(self):110- return 'UNPROCESSED'110+ return "UNPROCESSED"111 112 113 class StringParamType(ParamType):114- name = 'text'114+ name = "text"115 116 def convert(self, value, param, ctx):117 if isinstance(value, bytes):118 enc = _get_argv_encoding()4 unmodified lines123 if fs_enc != enc:124 try:125 value = value.decode(fs_enc)126 except UnicodeError:127- value = value.decode('utf-8', 'replace')127+ value = value.decode("utf-8", "replace")128 else:129- value = value.decode('utf-8', 'replace')129+ value = value.decode("utf-8", "replace")130 return value131 return value132 133 def __repr__(self):134- return 'STRING'134+ return "STRING"135 136 137 class Choice(ParamType):138 """The choice type allows a value to be checked against a fixed set11 unmodified lines150 :param case_sensitive: Set to false to make choices case151 insensitive. Defaults to true.152 """153 154- name = 'choice'154+ name = "choice"155 156 def __init__(self, choices, case_sensitive=True):157 self.choices = choices158 self.case_sensitive = case_sensitive159 160 def get_metavar(self, param):161- return '[%s]' % '|'.join(self.choices)161+ return "[%s]" % "|".join(self.choices)162 163 def get_missing_message(self, param):164- return 'Choose from:\n\t%s.' % ',\n\t'.join(self.choices)164+ return "Choose from:\n\t%s." % ",\n\t".join(self.choices)165 166 def convert(self, value, param, ctx):167 # Match through normalization and case sensitivity168 # first do token_normalize_func, then lowercase23 unmodified lines192 193 if normed_value in normed_choices:194 return normed_choices[normed_value]195 196- self.fail('invalid choice: %s. (choose from %s)' %197- (value, ', '.join(self.choices)), param, ctx)196+ self.fail(197+ "invalid choice: %s. (choose from %s)" % (value, ", ".join(self.choices)),198+ param,199+ ctx,200+ )201 202 def __repr__(self):200- return 'Choice(%r)' % list(self.choices)203+ return "Choice(%r)" % list(self.choices)204 205 206 class DateTime(ParamType):207 """The DateTime type converts date strings into `datetime` objects.14 unmodified lines222 which they should be tried. Defaults to223 ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,224 ``'%Y-%m-%d %H:%M:%S'``.225 """223- name = 'datetime'226 227+ name = "datetime"228+229 def __init__(self, formats=None):226- self.formats = formats or [227- '%Y-%m-%d',228- '%Y-%m-%dT%H:%M:%S',229- '%Y-%m-%d %H:%M:%S'230- ]230+ self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]231 232 def get_metavar(self, param):233- return '[{}]'.format('|'.join(self.formats))233+ return "[{}]".format("|".join(self.formats))234 235 def _try_to_convert_date(self, value, format):236 try:237 return datetime.strptime(value, format)7 unmodified lines245 if dtime:246 return dtime247 248 self.fail(249- 'invalid datetime format: {}. (choose from {})'.format(250- value, ', '.join(self.formats)))249+ "invalid datetime format: {}. (choose from {})".format(250+ value, ", ".join(self.formats)251+ )252+ )253 254 def __repr__(self):253- return 'DateTime'255+ return "DateTime"256 257 258 class IntParamType(ParamType):257- name = 'integer'259+ name = "integer"260 261 def convert(self, value, param, ctx):262 try:263 return int(value)264 except (ValueError, UnicodeError):263- self.fail('%s is not a valid integer' % value, param, ctx)265+ self.fail("%s is not a valid integer" % value, param, ctx)266 267 def __repr__(self):266- return 'INT'268+ return "INT"269 270 271 class IntRange(IntParamType):272 """A parameter that works similar to :data:`click.INT` but restricts2 unmodified lines275 between the two edges.276 277 See :ref:`ranges` for an example.278 """277- name = 'integer range'279 280+ name = "integer range"281+282 def __init__(self, min=None, max=None, clamp=False):283 self.min = min284 self.max = max285 self.clamp = clamp4 unmodified lines290 if self.min is not None and rv < self.min:291 return self.min292 if self.max is not None and rv > self.max:293 return self.max291- if self.min is not None and rv < self.min or \292- self.max is not None and rv > self.max:294+ if (295+ self.min is not None296+ and rv < self.min297+ or self.max is not None298+ and rv > self.max299+ ):300 if self.min is None:294- self.fail('%s is bigger than the maximum valid value '295- '%s.' % (rv, self.max), param, ctx)301+ self.fail(302+ "%s is bigger than the maximum valid value %s." % (rv, self.max),303+ param,304+ ctx,305+ )306 elif self.max is None:297- self.fail('%s is smaller than the minimum valid value '298- '%s.' % (rv, self.min), param, ctx)307+ self.fail(308+ "%s is smaller than the minimum valid value "309+ "%s." % (rv, self.min),310+ param,311+ ctx,312+ )313 else:300- self.fail('%s is not in the valid range of %s to %s.'301- % (rv, self.min, self.max), param, ctx)314+ self.fail(315+ "%s is not in the valid range of %s to %s."316+ % (rv, self.min, self.max),317+ param,318+ ctx,319+ )320 return rv321 322 def __repr__(self):305- return 'IntRange(%r, %r)' % (self.min, self.max)323+ return "IntRange(%r, %r)" % (self.min, self.max)324 325 326 class FloatParamType(ParamType):309- name = 'float'327+ name = "float"328 329 def convert(self, value, param, ctx):330 try:331 return float(value)332 except (UnicodeError, ValueError):315- self.fail('%s is not a valid floating point value' %316- value, param, ctx)333+ self.fail("%s is not a valid floating point value" % value, param, ctx)334 335 def __repr__(self):319- return 'FLOAT'336+ return "FLOAT"337 338 339 class FloatRange(FloatParamType):340 """A parameter that works similar to :data:`click.FLOAT` but restricts2 unmodified lines343 between the two edges.344 345 See :ref:`ranges` for an example.346 """330- name = 'float range'347 348+ name = "float range"349+350 def __init__(self, min=None, max=None, clamp=False):351 self.min = min352 self.max = max353 self.clamp = clamp4 unmodified lines358 if self.min is not None and rv < self.min:359 return self.min360 if self.max is not None and rv > self.max:361 return self.max344- if self.min is not None and rv < self.min or \345- self.max is not None and rv > self.max:362+ if (363+ self.min is not None364+ and rv < self.min365+ or self.max is not None366+ and rv > self.max367+ ):368 if self.min is None:347- self.fail('%s is bigger than the maximum valid value '348- '%s.' % (rv, self.max), param, ctx)369+ self.fail(370+ "%s is bigger than the maximum valid value %s." % (rv, self.max),371+ param,372+ ctx,373+ )374 elif self.max is None:350- self.fail('%s is smaller than the minimum valid value '351- '%s.' % (rv, self.min), param, ctx)375+ self.fail(376+ "%s is smaller than the minimum valid value "377+ "%s." % (rv, self.min),378+ param,379+ ctx,380+ )381 else:353- self.fail('%s is not in the valid range of %s to %s.'354- % (rv, self.min, self.max), param, ctx)382+ self.fail(383+ "%s is not in the valid range of %s to %s."384+ % (rv, self.min, self.max),385+ param,386+ ctx,387+ )388 return rv389 390 def __repr__(self):358- return 'FloatRange(%r, %r)' % (self.min, self.max)391+ return "FloatRange(%r, %r)" % (self.min, self.max)392 393 394 class BoolParamType(ParamType):362- name = 'boolean'395+ name = "boolean"396 397 def convert(self, value, param, ctx):398 if isinstance(value, bool):399 return bool(value)400 value = value.lower()368- if value in ('true', 't', '1', 'yes', 'y'):401+ if value in ("true", "t", "1", "yes", "y"):402 return True370- elif value in ('false', 'f', '0', 'no', 'n'):403+ elif value in ("false", "f", "0", "no", "n"):404 return False372- self.fail('%s is not a valid boolean' % value, param, ctx)405+ self.fail("%s is not a valid boolean" % value, param, ctx)406 407 def __repr__(self):375- return 'BOOL'408+ return "BOOL"409 410 411 class UUIDParameterType(ParamType):379- name = 'uuid'412+ name = "uuid"413 414 def convert(self, value, param, ctx):415 import uuid416+417 try:418 if PY2 and isinstance(value, text_type):385- value = value.encode('ascii')419+ value = value.encode("ascii")420 return uuid.UUID(value)421 except (UnicodeError, ValueError):388- self.fail('%s is not a valid UUID value' % value, param, ctx)422+ self.fail("%s is not a valid UUID value" % value, param, ctx)423 424 def __repr__(self):391- return 'UUID'425+ return "UUID"426 427 428 class File(ParamType):429 """Declares a parameter to be a file for reading or writing. The file20 unmodified lines450 is useful if a file regularly read by other users is modified.451 452 See :ref:`file-args` for more information.453 """420- name = 'filename'454+455+ name = "filename"456 envvar_list_splitter = os.path.pathsep457 423- def __init__(self, mode='r', encoding=None, errors='strict', lazy=None,424- atomic=False):458+ def __init__(459+ self, mode="r", encoding=None, errors="strict", lazy=None, atomic=False460+ ):461 self.mode = mode462 self.encoding = encoding463 self.errors = errors464 self.lazy = lazy1 unmodified line466 467 def resolve_lazy_flag(self, value):468 if self.lazy is not None:469 return self.lazy434- if value == '-':470+ if value == "-":471 return False436- elif 'w' in self.mode:472+ elif "w" in self.mode:473 return True474 return False475 476 def convert(self, value, param, ctx):477 try:442- if hasattr(value, 'read') or hasattr(value, 'write'):478+ if hasattr(value, "read") or hasattr(value, "write"):479 return value480 481 lazy = self.resolve_lazy_flag(value)482 483 if lazy:448- f = LazyFile(value, self.mode, self.encoding, self.errors,449- atomic=self.atomic)484+ f = LazyFile(485+ value, self.mode, self.encoding, self.errors, atomic=self.atomic486+ )487 if ctx is not None:488 ctx.call_on_close(f.close_intelligently)489 return f490 454- f, should_close = open_stream(value, self.mode,455- self.encoding, self.errors,456- atomic=self.atomic)491+ f, should_close = open_stream(492+ value, self.mode, self.encoding, self.errors, atomic=self.atomic493+ )494 # If a context is provided, we automatically close the file495 # at the end of the context execution (or flush out). If a496 # context does not exist, it's the caller's responsibility to497 # properly close the file. This for instance happens when the4 unmodified lines502 else:503 ctx.call_on_close(safecall(f.flush))504 return f505 except (IOError, OSError) as e:469- self.fail('Could not open file: %s: %s' % (470- filename_to_ui(value),471- get_streerror(e),472- ), param, ctx)506+ self.fail(507+ "Could not open file: %s: %s"508+ % (filename_to_ui(value), get_streerror(e),),509+ param,510+ ctx,511+ )512 513 514 class Path(ParamType):515 """The path type is similar to the :class:`File` type but it performs24 unmodified lines540 means the return value will be either bytes or541 unicode depending on what makes most sense given the542 input data Click deals with.543 """544+545 envvar_list_splitter = os.path.pathsep546 507- def __init__(self, exists=False, file_okay=True, dir_okay=True,508- writable=False, readable=True, resolve_path=False,509- allow_dash=False, path_type=None):547+ def __init__(548+ self,549+ exists=False,550+ file_okay=True,551+ dir_okay=True,552+ writable=False,553+ readable=True,554+ resolve_path=False,555+ allow_dash=False,556+ path_type=None,557+ ):558 self.exists = exists559 self.file_okay = file_okay560 self.dir_okay = dir_okay561 self.writable = writable2 unmodified lines564 self.allow_dash = allow_dash565 self.type = path_type566 567 if self.file_okay and not self.dir_okay:520- self.name = 'file'521- self.path_type = 'File'568+ self.name = "file"569+ self.path_type = "File"570 elif self.dir_okay and not self.file_okay:523- self.name = 'directory'524- self.path_type = 'Directory'571+ self.name = "directory"572+ self.path_type = "Directory"573 else:526- self.name = 'path'527- self.path_type = 'Path'574+ self.name = "path"575+ self.path_type = "Path"576 577 def coerce_path_result(self, rv):578 if self.type is not None and not isinstance(rv, self.type):579 if self.type is text_type:4 unmodified lines584 585 def convert(self, value, param, ctx):586 rv = value587 540- is_dash = self.file_okay and self.allow_dash and rv in (b'-', '-')588+ is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")589 590 if not is_dash:591 if self.resolve_path:592 rv = os.path.realpath(rv)2 unmodified lines595 st = os.stat(rv)596 except OSError:597 if not self.exists:598 return self.coerce_path_result(rv)551- self.fail('%s "%s" does not exist.' % (552- self.path_type,553- filename_to_ui(value)554- ), param, ctx)599+ self.fail(600+ '%s "%s" does not exist.' % (self.path_type, filename_to_ui(value)),601+ param,602+ ctx,603+ )604 605 if not self.file_okay and stat.S_ISREG(st.st_mode):557- self.fail('%s "%s" is a file.' % (558- self.path_type,559- filename_to_ui(value)560- ), param, ctx)606+ self.fail(607+ '%s "%s" is a file.' % (self.path_type, filename_to_ui(value)),608+ param,609+ ctx,610+ )611 if not self.dir_okay and stat.S_ISDIR(st.st_mode):562- self.fail('%s "%s" is a directory.' % (563- self.path_type,564- filename_to_ui(value)565- ), param, ctx)612+ self.fail(613+ '%s "%s" is a directory.' % (self.path_type, filename_to_ui(value)),614+ param,615+ ctx,616+ )617 if self.writable and not os.access(value, os.W_OK):567- self.fail('%s "%s" is not writable.' % (568- self.path_type,569- filename_to_ui(value)570- ), param, ctx)618+ self.fail(619+ '%s "%s" is not writable.'620+ % (self.path_type, filename_to_ui(value)),621+ param,622+ ctx,623+ )624 if self.readable and not os.access(value, os.R_OK):572- self.fail('%s "%s" is not readable.' % (573- self.path_type,574- filename_to_ui(value)575- ), param, ctx)625+ self.fail(626+ '%s "%s" is not readable.'627+ % (self.path_type, filename_to_ui(value)),628+ param,629+ ctx,630+ )631 632 return self.coerce_path_result(rv)633 634 23 unmodified lines658 return len(self.types)659 660 def convert(self, value, param, ctx):661 if len(value) != len(self.types):607- raise TypeError('It would appear that nargs is set to conflict '608- 'with the composite type arity.')662+ raise TypeError(663+ "It would appear that nargs is set to conflict "664+ "with the composite type arity."665+ )666 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))667 668 669 def convert_type(ty, default=None):30 unmodified lines700 # Catch a common mistake701 if __debug__:702 try:703 if issubclass(ty, ParamType):647- raise AssertionError('Attempted to use an uninstantiated '648- 'parameter type (%s).' % ty)704+ raise AssertionError(705+ "Attempted to use an uninstantiated parameter type (%s)." % ty706+ )707 except TypeError:708 pass709 return FuncParamType(ty)710 33 unmodified linesmodified:src/click/utils.py+40 added-36 removed
28 unmodified lines29 echo_native_types = string_types + (bytes, bytearray)30 31 32 def _posixify(name):33- return '-'.join(name.split()).lower()33+ return "-".join(name.split()).lower()34 35 36 def safecall(func):37 """Wraps a function so that it swallows exceptions."""38+39 def wrapper(*args, **kwargs):40 try:41 return func(*args, **kwargs)42 except Exception:43 pass44+45 return wrapper46 47 48 def make_str(value):1 unmodified line50 if isinstance(value, bytes):51 try:52 return value.decode(get_filesystem_encoding())53 except UnicodeError:52- return value.decode('utf-8', 'replace')54+ return value.decode("utf-8", "replace")55 return text_type(value)56 57 58 def make_default_short_help(help, max_length=45):3 unmodified lines62 result = []63 done = False64 65 for word in words:64- if word[-1:] == '.':66+ if word[-1:] == ".":67 done = True68 new_length = result and 1 + len(word) or len(word)69 if total_length + new_length > max_length:68- result.append('...')70+ result.append("...")71 done = True72 else:73 if result:72- result.append(' ')74+ result.append(" ")75 result.append(word)76 if done:77 break78 total_length += new_length79 78- return ''.join(result)80+ return "".join(result)81 82 83 class LazyFile(object):84 """A lazy file works like a regular file but it does not fully open1 unmodified line86 filename parameter does make sense. This is useful for safely opening87 files for writing.88 """89 88- def __init__(self, filename, mode='r', encoding=None, errors='strict',89- atomic=False):90+ def __init__(91+ self, filename, mode="r", encoding=None, errors="strict", atomic=False92+ ):93 self.name = filename94 self.mode = mode95 self.encoding = encoding96 self.errors = errors97 self.atomic = atomic98 96- if filename == '-':97- self._f, self.should_close = open_stream(filename, mode,98- encoding, errors)99+ if filename == "-":100+ self._f, self.should_close = open_stream(filename, mode, encoding, errors)101 else:100- if 'r' in mode:102+ if "r" in mode:103 # Open and close the file in case we're opening it for104 # reading so that we can catch at least some errors in105 # some cases early.106 open(filename, mode).close()5 unmodified lines112 113 def __repr__(self):114 if self._f is not None:115 return repr(self._f)114- return '<unopened file %r %s>' % (self.name, self.mode)116+ return "<unopened file %r %s>" % (self.name, self.mode)117 118 def open(self):119 """Opens the file if it's not yet open. This call might fail with120 a :exc:`FileError`. Not handling this error will produce an error1 unmodified line122 """123 if self._f is not None:124 return self._f125 try:124- rv, self.should_close = open_stream(self.name, self.mode,125- self.encoding,126- self.errors,127- atomic=self.atomic)126+ rv, self.should_close = open_stream(127+ self.name, self.mode, self.encoding, self.errors, atomic=self.atomic128+ )129 except (IOError, OSError) as e:130 from .exceptions import FileError131+132 raise FileError(self.name, hint=get_streerror(e))133 self._f = rv134 return rv135 20 unmodified lines156 return iter(self._f)157 158 159 class KeepOpenFile(object):158-160 def __init__(self, file):161 self._file = file162 163 def __getattr__(self, name):69 unmodified lines233 if message is not None and not isinstance(message, echo_native_types):234 message = text_type(message)235 236 if nl:236- message = message or u''237+ message = message or u""238 if isinstance(message, text_type):238- message += u'\n'239+ message += u"\n"240 else:240- message += b'\n'241+ message += b"\n"242 243 # If there is a message, and we're in Python 3, and the value looks244 # like bytes, we manually need to find the binary stream and write the245 # message in there. This is done separately so that most stream38 unmodified lines284 ``'stdout'`` and ``'stderr'``285 """286 opener = binary_streams.get(name)287 if opener is None:287- raise TypeError('Unknown standard stream %r' % name)288+ raise TypeError("Unknown standard stream %r" % name)289 return opener()290 291 291-def get_text_stream(name, encoding=None, errors='strict'):292+def get_text_stream(name, encoding=None, errors="strict"):293 """Returns a system stream for text processing. This usually returns294 a wrapped stream around a binary stream returned from295 :func:`get_binary_stream` but it also can take shortcuts on Python 3296 for already correctly configured streams.4 unmodified lines301 :param errors: overrides the default error mode.302 """303 opener = text_streams.get(name)304 if opener is None:304- raise TypeError('Unknown standard stream %r' % name)305+ raise TypeError("Unknown standard stream %r" % name)306 return opener(encoding, errors)307 308 308-def open_file(filename, mode='r', encoding=None, errors='strict',309- lazy=False, atomic=False):309+def open_file(310+ filename, mode="r", encoding=None, errors="strict", lazy=False, atomic=False311+):312 """This is similar to how the :class:`File` works but for manual313 usage. Files are opened non lazy by default. This can open regular314 files as well as stdin/stdout if ``'-'`` is passed.315 16 unmodified lines332 moved on close.333 """334 if lazy:335 return LazyFile(filename, mode, encoding, errors, atomic=atomic)334- f, should_close = open_stream(filename, mode, encoding, errors,335- atomic=atomic)336+ f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)337 if not should_close:338 f = KeepOpenFile(f)339 return f340 71 unmodified lines412 dot instead of the XDG config home or darwin's413 application support folder.414 """415 if WIN:415- key = roaming and 'APPDATA' or 'LOCALAPPDATA'416+ key = roaming and "APPDATA" or "LOCALAPPDATA"417 folder = os.environ.get(key)418 if folder is None:418- folder = os.path.expanduser('~')419+ folder = os.path.expanduser("~")420 return os.path.join(folder, app_name)421 if force_posix:421- return os.path.join(os.path.expanduser('~/.' + _posixify(app_name)))422- if sys.platform == 'darwin':423- return os.path.join(os.path.expanduser(424- '~/Library/Application Support'), app_name)422+ return os.path.join(os.path.expanduser("~/." + _posixify(app_name)))423+ if sys.platform == "darwin":424+ return os.path.join(425+ os.path.expanduser("~/Library/Application Support"), app_name426+ )427 return os.path.join(426- os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')),427- _posixify(app_name))428+ os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),429+ _posixify(app_name),430+ )431 432 433 class PacifyFlushWrapper(object):434 """This wrapper is used to catch and suppress BrokenPipeErrors resulting11 unmodified lines446 try:447 self.wrapped.flush()448 except IOError as e:449 import errno450+451 if e.errno != errno.EPIPE:452 raise453 454 def __getattr__(self, attr):1 unmodified linemodified:tests/conftest.py+1 added-1 removed
1 unmodified line2 3 from click.testing import CliRunner4 5 6-@pytest.fixture(scope='function')6+@pytest.fixture(scope="function")7 def runner(request):8 return CliRunner()modified:tests/test_arguments.py+115 added-106 removed
8 unmodified lines9 10 11 def test_nargs_star(runner):12 @click.command()13- @click.argument('src', nargs=-1)14- @click.argument('dst')13+ @click.argument("src", nargs=-1)14+ @click.argument("dst")15 def copy(src, dst):16- click.echo('src=%s' % '|'.join(src))17- click.echo('dst=%s' % dst)16+ click.echo("src=%s" % "|".join(src))17+ click.echo("dst=%s" % dst)18 19- result = runner.invoke(copy, ['foo.txt', 'bar.txt', 'dir'])19+ result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])20 assert not result.exception21 assert result.output.splitlines() == [22- 'src=foo.txt|bar.txt',23- 'dst=dir',22+ "src=foo.txt|bar.txt",23+ "dst=dir",24 ]25 26 27 def test_nargs_default(runner):28 try:29+30 @click.command()30- @click.argument('src', nargs=-1, default=42)31+ @click.argument("src", nargs=-1, default=42)32 def copy(src):33 pass34+35 except TypeError as e:34- assert 'nargs=-1' in str(e)36+ assert "nargs=-1" in str(e)37 else:38 assert False39 40 41 def test_nargs_tup(runner):42 @click.command()41- @click.argument('name', nargs=1)42- @click.argument('point', nargs=2, type=click.INT)43+ @click.argument("name", nargs=1)44+ @click.argument("point", nargs=2, type=click.INT)45 def copy(name, point):44- click.echo('name=%s' % name)45- click.echo('point=%d/%d' % point)46+ click.echo("name=%s" % name)47+ click.echo("point=%d/%d" % point)48 47- result = runner.invoke(copy, ['peter', '1', '2'])49+ result = runner.invoke(copy, ["peter", "1", "2"])50 assert not result.exception51 assert result.output.splitlines() == [50- 'name=peter',51- 'point=1/2',52+ "name=peter",53+ "point=1/2",54 ]55 56 57 def test_nargs_tup_composite(runner):4 unmodified lines62 dict(nargs=2, type=(str, int)),63 ]64 65 for opts in variations:66+67 @click.command()65- @click.argument('item', **opts)68+ @click.argument("item", **opts)69 def copy(item):67- click.echo('name=%s id=%d' % item)70+ click.echo("name=%s id=%d" % item)71 69- result = runner.invoke(copy, ['peter', '1'])72+ result = runner.invoke(copy, ["peter", "1"])73 assert not result.exception74 assert result.output.splitlines() == [72- 'name=peter id=1',75+ "name=peter id=1",76 ]77 78 79 def test_nargs_err(runner):80 @click.command()78- @click.argument('x')81+ @click.argument("x")82 def copy(x):83 click.echo(x)84 82- result = runner.invoke(copy, ['foo'])85+ result = runner.invoke(copy, ["foo"])86 assert not result.exception84- assert result.output == 'foo\n'87+ assert result.output == "foo\n"88 86- result = runner.invoke(copy, ['foo', 'bar'])89+ result = runner.invoke(copy, ["foo", "bar"])90 assert result.exit_code == 288- assert 'Got unexpected extra argument (bar)' in result.output91+ assert "Got unexpected extra argument (bar)" in result.output92 93 94 def test_bytes_args(runner, monkeypatch):95 @click.command()93- @click.argument('arg')96+ @click.argument("arg")97 def from_bytes(arg):95- assert isinstance(arg, text_type), "UTF-8 encoded argument should be implicitly converted to Unicode"98+ assert isinstance(99+ arg, text_type100+ ), "UTF-8 encoded argument should be implicitly converted to Unicode"101 102 # Simulate empty locale environment variables103 if PY2:99- monkeypatch.setattr(sys.stdin, 'encoding', 'ANSI_X3.4-1968')100- monkeypatch.setattr(sys, 'getfilesystemencoding', lambda: 'ANSI_X3.4-1968')101- monkeypatch.setattr(sys, 'getdefaultencoding', lambda: 'ascii')104+ monkeypatch.setattr(sys.stdin, "encoding", "ANSI_X3.4-1968")105+ monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "ANSI_X3.4-1968")106+ monkeypatch.setattr(sys, "getdefaultencoding", lambda: "ascii")107 else:103- monkeypatch.setattr(sys.stdin, 'encoding', 'utf-8')104- monkeypatch.setattr(sys, 'getfilesystemencoding', lambda: 'utf-8')105- monkeypatch.setattr(sys, 'getdefaultencoding', lambda: 'utf-8')108+ monkeypatch.setattr(sys.stdin, "encoding", "utf-8")109+ monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")110+ monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")111 107- runner.invoke(from_bytes, [u'Something outside of ASCII range: 林'.encode('UTF-8')],108- catch_exceptions=False)112+ runner.invoke(113+ from_bytes,114+ [u"Something outside of ASCII range: 林".encode("UTF-8")],115+ catch_exceptions=False,116+ )117 118 119 def test_file_args(runner):120 @click.command()113- @click.argument('input', type=click.File('rb'))114- @click.argument('output', type=click.File('wb'))121+ @click.argument("input", type=click.File("rb"))122+ @click.argument("output", type=click.File("wb"))123 def inout(input, output):124 while True:125 chunk = input.read(1024)126 if not chunk:127 break128 output.write(chunk)129 130 with runner.isolated_filesystem():123- result = runner.invoke(inout, ['-', 'hello.txt'], input='Hey!')124- assert result.output == ''131+ result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!")132+ assert result.output == ""133 assert result.exit_code == 0126- with open('hello.txt', 'rb') as f:127- assert f.read() == b'Hey!'134+ with open("hello.txt", "rb") as f:135+ assert f.read() == b"Hey!"136 129- result = runner.invoke(inout, ['hello.txt', '-'])130- assert result.output == 'Hey!'137+ result = runner.invoke(inout, ["hello.txt", "-"])138+ assert result.output == "Hey!"139 assert result.exit_code == 0140 141 142 def test_path_args(runner):143 @click.command()136- @click.argument('input', type=click.Path(dir_okay=False, allow_dash=True))144+ @click.argument("input", type=click.Path(dir_okay=False, allow_dash=True))145 def foo(input):146 click.echo(input)147 140- result = runner.invoke(foo, ['-'])141- assert result.output == '-\n'148+ result = runner.invoke(foo, ["-"])149+ assert result.output == "-\n"150 assert result.exit_code == 0151 152 153 def test_file_atomics(runner):154 @click.command()147- @click.argument('output', type=click.File('wb', atomic=True))155+ @click.argument("output", type=click.File("wb", atomic=True))156 def inout(output):149- output.write(b'Foo bar baz\n')157+ output.write(b"Foo bar baz\n")158 output.flush()151- with open(output.name, 'rb') as f:159+ with open(output.name, "rb") as f:160 old_content = f.read()153- assert old_content == b'OLD\n'161+ assert old_content == b"OLD\n"162 163 with runner.isolated_filesystem():156- with open('foo.txt', 'wb') as f:157- f.write(b'OLD\n')158- result = runner.invoke(inout, ['foo.txt'], input='Hey!',159- catch_exceptions=False)160- assert result.output == ''164+ with open("foo.txt", "wb") as f:165+ f.write(b"OLD\n")166+ result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False)167+ assert result.output == ""168 assert result.exit_code == 0162- with open('foo.txt', 'rb') as f:163- assert f.read() == b'Foo bar baz\n'169+ with open("foo.txt", "rb") as f:170+ assert f.read() == b"Foo bar baz\n"171 172 173 def test_stdout_default(runner):174 @click.command()168- @click.argument('output', type=click.File('w'), default='-')175+ @click.argument("output", type=click.File("w"), default="-")176 def inout(output):170- output.write('Foo bar baz\n')177+ output.write("Foo bar baz\n")178 output.flush()179 180 result = runner.invoke(inout, [])181 assert not result.exception175- assert result.output == 'Foo bar baz\n'182+ assert result.output == "Foo bar baz\n"183 184 185 def test_nargs_envvar(runner):186 @click.command()180- @click.option('--arg', nargs=2)187+ @click.option("--arg", nargs=2)188 def cmd(arg):182- click.echo('|'.join(arg))189+ click.echo("|".join(arg))190 184- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',185- env={'TEST_ARG': 'foo bar'})191+ result = runner.invoke(192+ cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}193+ )194 assert not result.exception187- assert result.output == 'foo|bar\n'195+ assert result.output == "foo|bar\n"196 197 @click.command()190- @click.option('--arg', envvar='X', nargs=2)198+ @click.option("--arg", envvar="X", nargs=2)199 def cmd(arg):192- click.echo('|'.join(arg))200+ click.echo("|".join(arg))201 194- result = runner.invoke(cmd, [], env={'X': 'foo bar'})202+ result = runner.invoke(cmd, [], env={"X": "foo bar"})203 assert not result.exception196- assert result.output == 'foo|bar\n'204+ assert result.output == "foo|bar\n"205 206 207 def test_empty_nargs(runner):208 @click.command()201- @click.argument('arg', nargs=-1)209+ @click.argument("arg", nargs=-1)210 def cmd(arg):203- click.echo('arg:' + '|'.join(arg))211+ click.echo("arg:" + "|".join(arg))212 213 result = runner.invoke(cmd, [])214 assert result.exit_code == 0207- assert result.output == 'arg:\n'215+ assert result.output == "arg:\n"216 217 @click.command()210- @click.argument('arg', nargs=-1, required=True)218+ @click.argument("arg", nargs=-1, required=True)219 def cmd2(arg):212- click.echo('arg:' + '|'.join(arg))220+ click.echo("arg:" + "|".join(arg))221 222 result = runner.invoke(cmd2, [])223 assert result.exit_code == 2224 assert 'Missing argument "ARG..."' in result.output225 226 227 def test_missing_arg(runner):228 @click.command()221- @click.argument('arg')229+ @click.argument("arg")230 def cmd(arg):223- click.echo('arg:' + arg)231+ click.echo("arg:" + arg)232 233 result = runner.invoke(cmd, [])234 assert result.exit_code == 2235 assert 'Missing argument "ARG".' in result.output9 unmodified lines245 246 247 def test_implicit_non_required(runner):248 @click.command()241- @click.argument('f', default='test')249+ @click.argument("f", default="test")250 def cli(f):251 click.echo(f)252 253 result = runner.invoke(cli, [])254 assert result.exit_code == 0247- assert result.output == 'test\n'255+ assert result.output == "test\n"256 257 258 def test_eat_options(runner):259 @click.command()252- @click.option('-f')253- @click.argument('files', nargs=-1)260+ @click.option("-f")261+ @click.argument("files", nargs=-1)262 def cmd(f, files):263 for filename in files:264 click.echo(filename)265 click.echo(f)266 259- result = runner.invoke(cmd, ['--', '-foo', 'bar'])267+ result = runner.invoke(cmd, ["--", "-foo", "bar"])268 assert result.output.splitlines() == [261- '-foo',262- 'bar',263- '',269+ "-foo",270+ "bar",271+ "",272 ]273 266- result = runner.invoke(cmd, ['-f', '-x', '--', '-foo', 'bar'])274+ result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"])275 assert result.output.splitlines() == [268- '-foo',269- 'bar',270- '-x',276+ "-foo",277+ "bar",278+ "-x",279 ]280 281 282 def test_nargs_star_ordering(runner):283 @click.command()276- @click.argument('a', nargs=-1)277- @click.argument('b')278- @click.argument('c')284+ @click.argument("a", nargs=-1)285+ @click.argument("b")286+ @click.argument("c")287 def cmd(a, b, c):288 for arg in (a, b, c):289 click.echo(arg)290 283- result = runner.invoke(cmd, ['a', 'b', 'c'])291+ result = runner.invoke(cmd, ["a", "b", "c"])292 assert result.output.splitlines() == [293 PY2 and "(u'a',)" or "('a',)",286- 'b',287- 'c',294+ "b",295+ "c",296 ]297 298 299 def test_nargs_specified_plus_star_ordering(runner):300 @click.command()293- @click.argument('a', nargs=-1)294- @click.argument('b')295- @click.argument('c', nargs=2)301+ @click.argument("a", nargs=-1)302+ @click.argument("b")303+ @click.argument("c", nargs=2)304 def cmd(a, b, c):305 for arg in (a, b, c):306 click.echo(arg)307 300- result = runner.invoke(cmd, ['a', 'b', 'c', 'd', 'e', 'f'])308+ result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])309 assert result.output.splitlines() == [310 PY2 and "(u'a', u'b', u'c')" or "('a', 'b', 'c')",303- 'd',311+ "d",312 PY2 and "(u'e', u'f')" or "('e', 'f')",313 ]314 315 316 def test_defaults_for_nargs(runner):317 @click.command()310- @click.argument('a', nargs=2, type=int, default=(1, 2))318+ @click.argument("a", nargs=2, type=int, default=(1, 2))319 def cmd(a):320 x, y = a321 click.echo(x + y)322 323 result = runner.invoke(cmd, [])316- assert result.output.strip() == '3'324+ assert result.output.strip() == "3"325 318- result = runner.invoke(cmd, ['3', '4'])319- assert result.output.strip() == '7'326+ result = runner.invoke(cmd, ["3", "4"])327+ assert result.output.strip() == "7"328 321- result = runner.invoke(cmd, ['3'])329+ result = runner.invoke(cmd, ["3"])330 assert result.exception is not None323- assert 'argument a takes 2 values' in result.output331+ assert "argument a takes 2 values" in result.output332 333 334 def test_multiple_param_decls_not_allowed(runner):335 with pytest.raises(TypeError):336+337 @click.command()329- @click.argument('x', click.Choice(['a', 'b']))338+ @click.argument("x", click.Choice(["a", "b"]))339 def copy(x):340 click.echo(x)modified:tests/test_bashcomplete.py+240 added-175 removed
4 unmodified lines5 from click._bashcomplete import get_choices6 7 8 def choices_without_help(cli, args, incomplete):9- completions = get_choices(cli, 'dummy', args, incomplete)9+ completions = get_choices(cli, "dummy", args, incomplete)10 return [c[0] for c in completions]11 12 13 def choices_with_help(cli, args, incomplete):14- return list(get_choices(cli, 'dummy', args, incomplete))14+ return list(get_choices(cli, "dummy", args, incomplete))15 16 17 def test_single_command():18 @click.command()19- @click.option('--local-opt')19+ @click.option("--local-opt")20 def cli(local_opt):21 pass22 23- assert choices_without_help(cli, [], '-') == ['--local-opt']24- assert choices_without_help(cli, [], '') == []23+ assert choices_without_help(cli, [], "-") == ["--local-opt"]24+ assert choices_without_help(cli, [], "") == []25 26 27 def test_boolean_flag():28 @click.command()29- @click.option('--shout/--no-shout', default=False)29+ @click.option("--shout/--no-shout", default=False)30 def cli(local_opt):31 pass32 33- assert choices_without_help(cli, [], '-') == ['--shout', '--no-shout']33+ assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout"]34 35 36 def test_multi_value_option():37 @click.group()38- @click.option('--pos', nargs=2, type=float)38+ @click.option("--pos", nargs=2, type=float)39 def cli(local_opt):40 pass41 42 @cli.command()43- @click.option('--local-opt')43+ @click.option("--local-opt")44 def sub(local_opt):45 pass46 47- assert choices_without_help(cli, [], '-') == ['--pos']48- assert choices_without_help(cli, ['--pos'], '') == []49- assert choices_without_help(cli, ['--pos', '1.0'], '') == []50- assert choices_without_help(cli, ['--pos', '1.0', '1.0'], '') == ['sub']47+ assert choices_without_help(cli, [], "-") == ["--pos"]48+ assert choices_without_help(cli, ["--pos"], "") == []49+ assert choices_without_help(cli, ["--pos", "1.0"], "") == []50+ assert choices_without_help(cli, ["--pos", "1.0", "1.0"], "") == ["sub"]51 52 53 def test_multi_option():54 @click.command()55- @click.option('--message', '-m', multiple=True)55+ @click.option("--message", "-m", multiple=True)56 def cli(local_opt):57 pass58 59- assert choices_without_help(cli, [], '-') == ['--message', '-m']60- assert choices_without_help(cli, ['-m'], '') == []59+ assert choices_without_help(cli, [], "-") == ["--message", "-m"]60+ assert choices_without_help(cli, ["-m"], "") == []61 62 63 def test_small_chain():64 @click.group()65- @click.option('--global-opt')65+ @click.option("--global-opt")66 def cli(global_opt):67 pass68 69 @cli.command()70- @click.option('--local-opt')70+ @click.option("--local-opt")71 def sub(local_opt):72 pass73 74- assert choices_without_help(cli, [], '') == ['sub']75- assert choices_without_help(cli, [], '-') == ['--global-opt']76- assert choices_without_help(cli, ['sub'], '') == []77- assert choices_without_help(cli, ['sub'], '-') == ['--local-opt']74+ assert choices_without_help(cli, [], "") == ["sub"]75+ assert choices_without_help(cli, [], "-") == ["--global-opt"]76+ assert choices_without_help(cli, ["sub"], "") == []77+ assert choices_without_help(cli, ["sub"], "-") == ["--local-opt"]78 79 80 def test_long_chain():81- @click.group('cli')82- @click.option('--cli-opt')81+ @click.group("cli")82+ @click.option("--cli-opt")83 def cli(cli_opt):84 pass85 86- @cli.group('asub')87- @click.option('--asub-opt')86+ @cli.group("asub")87+ @click.option("--asub-opt")88 def asub(asub_opt):89 pass90 91- @asub.group('bsub')92- @click.option('--bsub-opt')91+ @asub.group("bsub")92+ @click.option("--bsub-opt")93 def bsub(bsub_opt):94 pass95 96- COLORS = ['red', 'green', 'blue']96+ COLORS = ["red", "green", "blue"]97+98 def get_colors(ctx, args, incomplete):99 for c in COLORS:100 if c.startswith(incomplete):101 yield c2 unmodified lines104 for c in COLORS:105 if incomplete in c:106 yield c107 107- CSUB_OPT_CHOICES = ['foo', 'bar']108- CSUB_CHOICES = ['bar', 'baz']109- @bsub.command('csub')110- @click.option('--csub-opt', type=click.Choice(CSUB_OPT_CHOICES))111- @click.option('--csub', type=click.Choice(CSUB_CHOICES))112- @click.option('--search-color', autocompletion=search_colors)113- @click.argument('color', autocompletion=get_colors)108+ CSUB_OPT_CHOICES = ["foo", "bar"]109+ CSUB_CHOICES = ["bar", "baz"]110+111+ @bsub.command("csub")112+ @click.option("--csub-opt", type=click.Choice(CSUB_OPT_CHOICES))113+ @click.option("--csub", type=click.Choice(CSUB_CHOICES))114+ @click.option("--search-color", autocompletion=search_colors)115+ @click.argument("color", autocompletion=get_colors)116 def csub(csub_opt, color):117 pass118 117- assert choices_without_help(cli, [], '-') == ['--cli-opt']118- assert choices_without_help(cli, [], '') == ['asub']119- assert choices_without_help(cli, ['asub'], '-') == ['--asub-opt']120- assert choices_without_help(cli, ['asub'], '') == ['bsub']121- assert choices_without_help(cli, ['asub', 'bsub'], '-') == ['--bsub-opt']122- assert choices_without_help(cli, ['asub', 'bsub'], '') == ['csub']123- assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '-') == ['--csub-opt', '--csub', '--search-color']124- assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub-opt'], '') == CSUB_OPT_CHOICES125- assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '--csub') == ['--csub-opt', '--csub']126- assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub'], '') == CSUB_CHOICES127- assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--csub-opt'], 'f') == ['foo']128- assert choices_without_help(cli, ['asub', 'bsub', 'csub'], '') == COLORS129- assert choices_without_help(cli, ['asub', 'bsub', 'csub'], 'b') == ['blue']130- assert choices_without_help(cli, ['asub', 'bsub', 'csub', '--search-color'], 'een') == ['green']119+ assert choices_without_help(cli, [], "-") == ["--cli-opt"]120+ assert choices_without_help(cli, [], "") == ["asub"]121+ assert choices_without_help(cli, ["asub"], "-") == ["--asub-opt"]122+ assert choices_without_help(cli, ["asub"], "") == ["bsub"]123+ assert choices_without_help(cli, ["asub", "bsub"], "-") == ["--bsub-opt"]124+ assert choices_without_help(cli, ["asub", "bsub"], "") == ["csub"]125+ assert choices_without_help(cli, ["asub", "bsub", "csub"], "-") == [126+ "--csub-opt",127+ "--csub",128+ "--search-color",129+ ]130+ assert (131+ choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "")132+ == CSUB_OPT_CHOICES133+ )134+ assert choices_without_help(cli, ["asub", "bsub", "csub"], "--csub") == [135+ "--csub-opt",136+ "--csub",137+ ]138+ assert (139+ choices_without_help(cli, ["asub", "bsub", "csub", "--csub"], "")140+ == CSUB_CHOICES141+ )142+ assert choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "f") == [143+ "foo"144+ ]145+ assert choices_without_help(cli, ["asub", "bsub", "csub"], "") == COLORS146+ assert choices_without_help(cli, ["asub", "bsub", "csub"], "b") == ["blue"]147+ assert choices_without_help(148+ cli, ["asub", "bsub", "csub", "--search-color"], "een"149+ ) == ["green"]150 151 152 def test_chaining():134- @click.group('cli', chain=True)135- @click.option('--cli-opt')136- @click.argument('arg', type=click.Choice(['cliarg1', 'cliarg2']))153+ @click.group("cli", chain=True)154+ @click.option("--cli-opt")155+ @click.argument("arg", type=click.Choice(["cliarg1", "cliarg2"]))156 def cli(cli_opt, arg):157 pass158 159 @cli.command()141- @click.option('--asub-opt')160+ @click.option("--asub-opt")161 def asub(asub_opt):162 pass163 145- @cli.command(help='bsub help')146- @click.option('--bsub-opt')147- @click.argument('arg', type=click.Choice(['arg1', 'arg2']))164+ @cli.command(help="bsub help")165+ @click.option("--bsub-opt")166+ @click.argument("arg", type=click.Choice(["arg1", "arg2"]))167 def bsub(bsub_opt, arg):168 pass169 170 @cli.command()152- @click.option('--csub-opt')153- @click.argument('arg', type=click.Choice(['carg1', 'carg2']), default='carg1')171+ @click.option("--csub-opt")172+ @click.argument("arg", type=click.Choice(["carg1", "carg2"]), default="carg1")173 def csub(csub_opt, arg):174 pass175 157- assert choices_without_help(cli, [], '-') == ['--cli-opt']158- assert choices_without_help(cli, [], '') == ['cliarg1', 'cliarg2']159- assert choices_without_help(cli, ['cliarg1', 'asub'], '-') == ['--asub-opt']160- assert choices_without_help(cli, ['cliarg1', 'asub'], '') == ['bsub', 'csub']161- assert choices_without_help(cli, ['cliarg1', 'bsub'], '') == ['arg1', 'arg2']162- assert choices_without_help(cli, ['cliarg1', 'asub', '--asub-opt'], '') == []163- assert choices_without_help(cli, ['cliarg1', 'asub', '--asub-opt', '5', 'bsub'], '-') == ['--bsub-opt']164- assert choices_without_help(cli, ['cliarg1', 'asub', 'bsub'], '-') == ['--bsub-opt']165- assert choices_without_help(cli, ['cliarg1', 'asub', 'csub'], '') == ['carg1', 'carg2']166- assert choices_without_help(cli, ['cliarg1', 'bsub', 'arg1', 'csub'], '') == ['carg1', 'carg2']167- assert choices_without_help(cli, ['cliarg1', 'asub', 'csub'], '-') == ['--csub-opt']168- assert choices_with_help(cli, ['cliarg1', 'asub'], 'b') == [('bsub', 'bsub help')]176+ assert choices_without_help(cli, [], "-") == ["--cli-opt"]177+ assert choices_without_help(cli, [], "") == ["cliarg1", "cliarg2"]178+ assert choices_without_help(cli, ["cliarg1", "asub"], "-") == ["--asub-opt"]179+ assert choices_without_help(cli, ["cliarg1", "asub"], "") == ["bsub", "csub"]180+ assert choices_without_help(cli, ["cliarg1", "bsub"], "") == ["arg1", "arg2"]181+ assert choices_without_help(cli, ["cliarg1", "asub", "--asub-opt"], "") == []182+ assert choices_without_help(183+ cli, ["cliarg1", "asub", "--asub-opt", "5", "bsub"], "-"184+ ) == ["--bsub-opt"]185+ assert choices_without_help(cli, ["cliarg1", "asub", "bsub"], "-") == ["--bsub-opt"]186+ assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "") == [187+ "carg1",188+ "carg2",189+ ]190+ assert choices_without_help(cli, ["cliarg1", "bsub", "arg1", "csub"], "") == [191+ "carg1",192+ "carg2",193+ ]194+ assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "-") == ["--csub-opt"]195+ assert choices_with_help(cli, ["cliarg1", "asub"], "b") == [("bsub", "bsub help")]196 197 198 def test_argument_choice():199 @click.command()173- @click.argument('arg1', required=True, type=click.Choice(['arg11', 'arg12']))174- @click.argument('arg2', type=click.Choice(['arg21', 'arg22']), default='arg21')175- @click.argument('arg3', type=click.Choice(['arg', 'argument']), default='arg')200+ @click.argument("arg1", required=True, type=click.Choice(["arg11", "arg12"]))201+ @click.argument("arg2", type=click.Choice(["arg21", "arg22"]), default="arg21")202+ @click.argument("arg3", type=click.Choice(["arg", "argument"]), default="arg")203 def cli():204 pass205 179- assert choices_without_help(cli, [], '') == ['arg11', 'arg12']180- assert choices_without_help(cli, [], 'arg') == ['arg11', 'arg12']181- assert choices_without_help(cli, ['arg11'], '') == ['arg21', 'arg22']182- assert choices_without_help(cli, ['arg12', 'arg21'], '') == ['arg', 'argument']183- assert choices_without_help(cli, ['arg12', 'arg21'], 'argu') == ['argument']206+ assert choices_without_help(cli, [], "") == ["arg11", "arg12"]207+ assert choices_without_help(cli, [], "arg") == ["arg11", "arg12"]208+ assert choices_without_help(cli, ["arg11"], "") == ["arg21", "arg22"]209+ assert choices_without_help(cli, ["arg12", "arg21"], "") == ["arg", "argument"]210+ assert choices_without_help(cli, ["arg12", "arg21"], "argu") == ["argument"]211 212 213 def test_option_choice():214 @click.command()188- @click.option('--opt1', type=click.Choice(['opt11', 'opt12']), help='opt1 help')189- @click.option('--opt2', type=click.Choice(['opt21', 'opt22']), default='opt21')190- @click.option('--opt3', type=click.Choice(['opt', 'option']))215+ @click.option("--opt1", type=click.Choice(["opt11", "opt12"]), help="opt1 help")216+ @click.option("--opt2", type=click.Choice(["opt21", "opt22"]), default="opt21")217+ @click.option("--opt3", type=click.Choice(["opt", "option"]))218 def cli():219 pass220 194- assert choices_with_help(cli, [], '-') == [('--opt1', 'opt1 help'),195- ('--opt2', None),196- ('--opt3', None)]197- assert choices_without_help(cli, [], '--opt') == ['--opt1', '--opt2', '--opt3']198- assert choices_without_help(cli, [], '--opt1=') == ['opt11', 'opt12']199- assert choices_without_help(cli, [], '--opt2=') == ['opt21', 'opt22']200- assert choices_without_help(cli, ['--opt2'], '=') == ['opt21', 'opt22']201- assert choices_without_help(cli, ['--opt2', '='], 'opt') == ['opt21', 'opt22']202- assert choices_without_help(cli, ['--opt1'], '') == ['opt11', 'opt12']203- assert choices_without_help(cli, ['--opt2'], '') == ['opt21', 'opt22']204- assert choices_without_help(cli, ['--opt1', 'opt11', '--opt2'], '') == ['opt21', 'opt22']205- assert choices_without_help(cli, ['--opt2', 'opt21'], '-') == ['--opt1', '--opt3']206- assert choices_without_help(cli, ['--opt1', 'opt11'], '-') == ['--opt2', '--opt3']207- assert choices_without_help(cli, ['--opt1'], 'opt') == ['opt11', 'opt12']208- assert choices_without_help(cli, ['--opt3'], 'opti') == ['option']221+ assert choices_with_help(cli, [], "-") == [222+ ("--opt1", "opt1 help"),223+ ("--opt2", None),224+ ("--opt3", None),225+ ]226+ assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2", "--opt3"]227+ assert choices_without_help(cli, [], "--opt1=") == ["opt11", "opt12"]228+ assert choices_without_help(cli, [], "--opt2=") == ["opt21", "opt22"]229+ assert choices_without_help(cli, ["--opt2"], "=") == ["opt21", "opt22"]230+ assert choices_without_help(cli, ["--opt2", "="], "opt") == ["opt21", "opt22"]231+ assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"]232+ assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"]233+ assert choices_without_help(cli, ["--opt1", "opt11", "--opt2"], "") == [234+ "opt21",235+ "opt22",236+ ]237+ assert choices_without_help(cli, ["--opt2", "opt21"], "-") == ["--opt1", "--opt3"]238+ assert choices_without_help(cli, ["--opt1", "opt11"], "-") == ["--opt2", "--opt3"]239+ assert choices_without_help(cli, ["--opt1"], "opt") == ["opt11", "opt12"]240+ assert choices_without_help(cli, ["--opt3"], "opti") == ["option"]241 210- assert choices_without_help(cli, ['--opt1', 'invalid_opt'], '-') == ['--opt2', '--opt3']242+ assert choices_without_help(cli, ["--opt1", "invalid_opt"], "-") == [243+ "--opt2",244+ "--opt3",245+ ]246 247 248 def test_option_and_arg_choice():249 @click.command()215- @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))216- @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))217- @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))250+ @click.option("--opt1", type=click.Choice(["opt11", "opt12"]))251+ @click.argument("arg1", required=False, type=click.Choice(["arg11", "arg12"]))252+ @click.option("--opt2", type=click.Choice(["opt21", "opt22"]))253 def cli():254 pass255 221- assert choices_without_help(cli, ['--opt1'], '') == ['opt11', 'opt12']222- assert choices_without_help(cli, [''], '--opt1=') == ['opt11', 'opt12']223- assert choices_without_help(cli, [], '') == ['arg11', 'arg12']224- assert choices_without_help(cli, ['--opt2'], '') == ['opt21', 'opt22']225- assert choices_without_help(cli, ['arg11'], '--opt') == ['--opt1', '--opt2']226- assert choices_without_help(cli, [], '--opt') == ['--opt1', '--opt2']256+ assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"]257+ assert choices_without_help(cli, [""], "--opt1=") == ["opt11", "opt12"]258+ assert choices_without_help(cli, [], "") == ["arg11", "arg12"]259+ assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"]260+ assert choices_without_help(cli, ["arg11"], "--opt") == ["--opt1", "--opt2"]261+ assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2"]262 263 264 def test_boolean_flag_choice():265 @click.command()231- @click.option('--shout/--no-shout', default=False)232- @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))266+ @click.option("--shout/--no-shout", default=False)267+ @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))268 def cli(local_opt):269 pass270 236- assert choices_without_help(cli, [], '-') == ['--shout', '--no-shout']237- assert choices_without_help(cli, ['--shout'], '') == ['arg1', 'arg2']271+ assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout"]272+ assert choices_without_help(cli, ["--shout"], "") == ["arg1", "arg2"]273 274 275 def test_multi_value_option_choice():276 @click.command()242- @click.option('--pos', nargs=2, type=click.Choice(['pos1', 'pos2']))243- @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))277+ @click.option("--pos", nargs=2, type=click.Choice(["pos1", "pos2"]))278+ @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))279 def cli(local_opt):280 pass281 247- assert choices_without_help(cli, ['--pos'], '') == ['pos1', 'pos2']248- assert choices_without_help(cli, ['--pos', 'pos1'], '') == ['pos1', 'pos2']249- assert choices_without_help(cli, ['--pos', 'pos1', 'pos2'], '') == ['arg1', 'arg2']250- assert choices_without_help(cli, ['--pos', 'pos1', 'pos2', 'arg1'], '') == []282+ assert choices_without_help(cli, ["--pos"], "") == ["pos1", "pos2"]283+ assert choices_without_help(cli, ["--pos", "pos1"], "") == ["pos1", "pos2"]284+ assert choices_without_help(cli, ["--pos", "pos1", "pos2"], "") == ["arg1", "arg2"]285+ assert choices_without_help(cli, ["--pos", "pos1", "pos2", "arg1"], "") == []286 287 288 def test_multi_option_choice():289 @click.command()255- @click.option('--message', '-m', multiple=True, type=click.Choice(['m1', 'm2']))256- @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))290+ @click.option("--message", "-m", multiple=True, type=click.Choice(["m1", "m2"]))291+ @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))292 def cli(local_opt):293 pass294 260- assert choices_without_help(cli, ['-m'], '') == ['m1', 'm2']261- assert choices_without_help(cli, ['-m', 'm1', '-m'], '') == ['m1', 'm2']262- assert choices_without_help(cli, ['-m', 'm1'], '') == ['arg1', 'arg2']295+ assert choices_without_help(cli, ["-m"], "") == ["m1", "m2"]296+ assert choices_without_help(cli, ["-m", "m1", "-m"], "") == ["m1", "m2"]297+ assert choices_without_help(cli, ["-m", "m1"], "") == ["arg1", "arg2"]298 299 300 def test_variadic_argument_choice():301 @click.command()267- @click.option('--opt', type=click.Choice(['opt1', 'opt2']))268- @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))302+ @click.option("--opt", type=click.Choice(["opt1", "opt2"]))303+ @click.argument("src", nargs=-1, type=click.Choice(["src1", "src2"]))304 def cli(local_opt):305 pass306 272- assert choices_without_help(cli, ['src1', 'src2'], '') == ['src1', 'src2']273- assert choices_without_help(cli, ['src1', 'src2'], '--o') == ['--opt']274- assert choices_without_help(cli, ['src1', 'src2', '--opt'], '') == ['opt1', 'opt2']275- assert choices_without_help(cli, ['src1', 'src2'], '') == ['src1', 'src2']307+ assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"]308+ assert choices_without_help(cli, ["src1", "src2"], "--o") == ["--opt"]309+ assert choices_without_help(cli, ["src1", "src2", "--opt"], "") == ["opt1", "opt2"]310+ assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"]311 312 313 def test_variadic_argument_complete():279-314 def _complete(ctx, args, incomplete):281- return ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz']315+ return ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]316 317 @click.group()318 def entrypoint():319 pass320 321 @click.command()288- @click.option('--opt', autocompletion=_complete)289- @click.argument('arg', nargs=-1)322+ @click.option("--opt", autocompletion=_complete)323+ @click.argument("arg", nargs=-1)324 def subcommand(opt, arg):325 pass326 327 entrypoint.add_command(subcommand)328 295- assert choices_without_help(entrypoint, ['subcommand', '--opt'], '') == _complete(0,0,0)296- assert choices_without_help(entrypoint, ['subcommand', 'whatever', '--opt'], '') == _complete(0,0,0)297- assert choices_without_help(entrypoint, ['subcommand', 'whatever', '--opt', 'abc'], '') == []329+ assert choices_without_help(entrypoint, ["subcommand", "--opt"], "") == _complete(330+ 0, 0, 0331+ )332+ assert choices_without_help(333+ entrypoint, ["subcommand", "whatever", "--opt"], ""334+ ) == _complete(0, 0, 0)335+ assert (336+ choices_without_help(entrypoint, ["subcommand", "whatever", "--opt", "abc"], "")337+ == []338+ )339 340 341 def test_long_chain_choice():342 @click.group()343 def cli():344 pass345 346 @cli.group()306- @click.option('--sub-opt', type=click.Choice(['subopt1', 'subopt2']))307- @click.argument('sub-arg', required=False, type=click.Choice(['subarg1', 'subarg2']))347+ @click.option("--sub-opt", type=click.Choice(["subopt1", "subopt2"]))348+ @click.argument(349+ "sub-arg", required=False, type=click.Choice(["subarg1", "subarg2"])350+ )351 def sub(sub_opt, sub_arg):352 pass353 311- @sub.command(short_help='bsub help')312- @click.option('--bsub-opt', type=click.Choice(['bsubopt1', 'bsubopt2']))313- @click.argument('bsub-arg1', required=False, type=click.Choice(['bsubarg1', 'bsubarg2']))314- @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))354+ @sub.command(short_help="bsub help")355+ @click.option("--bsub-opt", type=click.Choice(["bsubopt1", "bsubopt2"]))356+ @click.argument(357+ "bsub-arg1", required=False, type=click.Choice(["bsubarg1", "bsubarg2"])358+ )359+ @click.argument(360+ "bbsub-arg2", required=False, type=click.Choice(["bbsubarg1", "bbsubarg2"])361+ )362 def bsub(bsub_opt):363 pass364 318- @sub.group('csub')365+ @sub.group("csub")366 def csub():367 pass368 369 @csub.command()370 def dsub():371 pass372 326- assert choices_with_help(cli, ['sub', 'subarg1'], '') == [('bsub', 'bsub help'), ('csub', '')]327- assert choices_without_help(cli, ['sub'], '') == ['subarg1', 'subarg2']328- assert choices_without_help(cli, ['sub', '--sub-opt'], '') == ['subopt1', 'subopt2']329- assert choices_without_help(cli, ['sub', '--sub-opt', 'subopt1'], '') == \330- ['subarg1', 'subarg2']331- assert choices_without_help(cli,332- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '-') == ['--bsub-opt']333- assert choices_without_help(cli,334- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '') == ['bsubarg1', 'bsubarg2']335- assert choices_without_help(cli,336- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt'], '') == \337- ['bsubopt1', 'bsubopt2']338- assert choices_without_help(cli,339- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt', 'bsubopt1', 'bsubarg1'],340- '') == ['bbsubarg1', 'bbsubarg2']341- assert choices_without_help(cli,342- ['sub', '--sub-opt', 'subopt1', 'subarg1', 'csub'],343- '') == ['dsub']373+ assert choices_with_help(cli, ["sub", "subarg1"], "") == [374+ ("bsub", "bsub help"),375+ ("csub", ""),376+ ]377+ assert choices_without_help(cli, ["sub"], "") == ["subarg1", "subarg2"]378+ assert choices_without_help(cli, ["sub", "--sub-opt"], "") == ["subopt1", "subopt2"]379+ assert choices_without_help(cli, ["sub", "--sub-opt", "subopt1"], "") == [380+ "subarg1",381+ "subarg2",382+ ]383+ assert choices_without_help(384+ cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], "-"385+ ) == ["--bsub-opt"]386+ assert choices_without_help(387+ cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], ""388+ ) == ["bsubarg1", "bsubarg2"]389+ assert choices_without_help(390+ cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub", "--bsub-opt"], ""391+ ) == ["bsubopt1", "bsubopt2"]392+ assert choices_without_help(393+ cli,394+ [395+ "sub",396+ "--sub-opt",397+ "subopt1",398+ "subarg1",399+ "bsub",400+ "--bsub-opt",401+ "bsubopt1",402+ "bsubarg1",403+ ],404+ "",405+ ) == ["bbsubarg1", "bbsubarg2"]406+ assert choices_without_help(407+ cli, ["sub", "--sub-opt", "subopt1", "subarg1", "csub"], ""408+ ) == ["dsub"]409 410 411 def test_chained_multi():412 @click.group()19 unmodified lines432 @csub.command()433 def esub():434 pass435 371- assert choices_without_help(cli, ['sub'], '') == ['bsub', 'csub']372- assert choices_without_help(cli, ['sub'], 'c') == ['csub']373- assert choices_without_help(cli, ['sub', 'csub'], '') == ['dsub', 'esub']374- assert choices_without_help(cli, ['sub', 'csub', 'dsub'], '') == ['esub']436+ assert choices_without_help(cli, ["sub"], "") == ["bsub", "csub"]437+ assert choices_without_help(cli, ["sub"], "c") == ["csub"]438+ assert choices_without_help(cli, ["sub", "csub"], "") == ["dsub", "esub"]439+ assert choices_without_help(cli, ["sub", "csub", "dsub"], "") == ["esub"]440 441 442 def test_hidden():443 @click.group()379- @click.option('--name', hidden=True)380- @click.option('--choices', type=click.Choice([1, 2]), hidden=True)444+ @click.option("--name", hidden=True)445+ @click.option("--choices", type=click.Choice([1, 2]), hidden=True)446 def cli(name):447 pass448 449 @cli.group(hidden=True)8 unmodified lines458 def asub():459 pass460 461 @cli.command(hidden=True)397- @click.option('--hname')462+ @click.option("--hname")463 def hsub():464 pass465 401- assert choices_without_help(cli, [], '--n') == []402- assert choices_without_help(cli, [], '--c') == []466+ assert choices_without_help(cli, [], "--n") == []467+ assert choices_without_help(cli, [], "--c") == []468 # If the user exactly types out the hidden param, complete its options.404- assert choices_without_help(cli, ['--choices'], '') == [1, 2]405- assert choices_without_help(cli, [], '') == ['asub']406- assert choices_without_help(cli, [], '') == ['asub']407- assert choices_without_help(cli, [], 'h') == []469+ assert choices_without_help(cli, ["--choices"], "") == [1, 2]470+ assert choices_without_help(cli, [], "") == ["asub"]471+ assert choices_without_help(cli, [], "") == ["asub"]472+ assert choices_without_help(cli, [], "h") == []473 # If the user exactly types out the hidden command, complete its subcommands.409- assert choices_without_help(cli, ['hgroup'], '') == ['hgroupsub']410- assert choices_without_help(cli, ['hsub'], '--h') == ['--hname']474+ assert choices_without_help(cli, ["hgroup"], "") == ["hgroupsub"]475+ assert choices_without_help(cli, ["hsub"], "--h") == ["--hname"]476 477 478 @pytest.mark.parametrize(479 ("args", "part", "expect"),21 unmodified linesmodified:tests/test_basic.py+217 added-207 removed
7 unmodified lines8 def test_basic_functionality(runner):9 @click.command()10 def cli():11 """Hello World!"""12- click.echo('I EXECUTED')12+ click.echo("I EXECUTED")13 14- result = runner.invoke(cli, ['--help'])14+ result = runner.invoke(cli, ["--help"])15 assert not result.exception16- assert 'Hello World!' in result.output17- assert 'Show this message and exit.' in result.output16+ assert "Hello World!" in result.output17+ assert "Show this message and exit." in result.output18 assert result.exit_code == 019- assert 'I EXECUTED' not in result.output19+ assert "I EXECUTED" not in result.output20 21 result = runner.invoke(cli, [])22 assert not result.exception23- assert 'I EXECUTED' in result.output23+ assert "I EXECUTED" in result.output24 assert result.exit_code == 025 26 27 def test_repr():8 unmodified lines36 @group.command()37 def subcommand():38 pass39 40- assert repr(command) == '<Command command>'41- assert repr(group) == '<Group group>'42- assert repr(subcommand) == '<Command subcommand>'40+ assert repr(command) == "<Command command>"41+ assert repr(group) == "<Group group>"42+ assert repr(subcommand) == "<Command subcommand>"43 44 45 def test_return_values():46 @click.command()47 def cli():48 return 4249 50- with cli.make_context('foo', []) as ctx:50+ with cli.make_context("foo", []) as ctx:51 rv = cli.invoke(ctx)52 assert rv is 4253 54 55 def test_basic_group(runner):56 @click.group()57 def cli():58 """This is the root."""59- click.echo('ROOT EXECUTED')59+ click.echo("ROOT EXECUTED")60 61 @cli.command()62 def subcommand():63 """This is a subcommand."""64- click.echo('SUBCOMMAND EXECUTED')64+ click.echo("SUBCOMMAND EXECUTED")65 66- result = runner.invoke(cli, ['--help'])66+ result = runner.invoke(cli, ["--help"])67 assert not result.exception68- assert 'COMMAND [ARGS]...' in result.output69- assert 'This is the root' in result.output70- assert 'This is a subcommand.' in result.output68+ assert "COMMAND [ARGS]..." in result.output69+ assert "This is the root" in result.output70+ assert "This is a subcommand." in result.output71 assert result.exit_code == 072- assert 'ROOT EXECUTED' not in result.output72+ assert "ROOT EXECUTED" not in result.output73 74- result = runner.invoke(cli, ['subcommand'])74+ result = runner.invoke(cli, ["subcommand"])75 assert not result.exception76 assert result.exit_code == 077- assert 'ROOT EXECUTED' in result.output78- assert 'SUBCOMMAND EXECUTED' in result.output77+ assert "ROOT EXECUTED" in result.output78+ assert "SUBCOMMAND EXECUTED" in result.output79 80 81 def test_basic_option(runner):82 @click.command()83- @click.option('--foo', default='no value')83+ @click.option("--foo", default="no value")84 def cli(foo):85- click.echo('FOO:[%s]' % foo)85+ click.echo("FOO:[%s]" % foo)86 87 result = runner.invoke(cli, [])88 assert not result.exception89- assert 'FOO:[no value]' in result.output89+ assert "FOO:[no value]" in result.output90 91- result = runner.invoke(cli, ['--foo=42'])91+ result = runner.invoke(cli, ["--foo=42"])92 assert not result.exception93- assert 'FOO:[42]' in result.output93+ assert "FOO:[42]" in result.output94 95- result = runner.invoke(cli, ['--foo'])95+ result = runner.invoke(cli, ["--foo"])96 assert result.exception97- assert '--foo option requires an argument' in result.output97+ assert "--foo option requires an argument" in result.output98 99- result = runner.invoke(cli, ['--foo='])99+ result = runner.invoke(cli, ["--foo="])100 assert not result.exception101- assert 'FOO:[]' in result.output101+ assert "FOO:[]" in result.output102 103- result = runner.invoke(cli, [u'--foo=\N{SNOWMAN}'])103+ result = runner.invoke(cli, [u"--foo=\N{SNOWMAN}"])104 assert not result.exception105- assert u'FOO:[\N{SNOWMAN}]' in result.output105+ assert u"FOO:[\N{SNOWMAN}]" in result.output106 107 108 def test_int_option(runner):109 @click.command()110- @click.option('--foo', default=42)110+ @click.option("--foo", default=42)111 def cli(foo):112- click.echo('FOO:[%s]' % (foo * 2))112+ click.echo("FOO:[%s]" % (foo * 2))113 114 result = runner.invoke(cli, [])115 assert not result.exception116- assert 'FOO:[84]' in result.output116+ assert "FOO:[84]" in result.output117 118- result = runner.invoke(cli, ['--foo=23'])118+ result = runner.invoke(cli, ["--foo=23"])119 assert not result.exception120- assert 'FOO:[46]' in result.output120+ assert "FOO:[46]" in result.output121 122- result = runner.invoke(cli, ['--foo=bar'])122+ result = runner.invoke(cli, ["--foo=bar"])123 assert result.exception124- assert 'Invalid value for "--foo": bar is not a valid integer' \125- in result.output124+ assert 'Invalid value for "--foo": bar is not a valid integer' in result.output125 126 127 def test_uuid_option(runner):128 @click.command()130- @click.option('--u', default='ba122011-349f-423b-873b-9d6a79c688ab',131- type=click.UUID)129+ @click.option(130+ "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID131+ )132 def cli(u):133 assert type(u) is uuid.UUID134- click.echo('U:[%s]' % u)134+ click.echo("U:[%s]" % u)135 136 result = runner.invoke(cli, [])137 assert not result.exception138- assert 'U:[ba122011-349f-423b-873b-9d6a79c688ab]' in result.output138+ assert "U:[ba122011-349f-423b-873b-9d6a79c688ab]" in result.output139 140- result = runner.invoke(cli, ['--u=821592c1-c50e-4971-9cd6-e89dc6832f86'])140+ result = runner.invoke(cli, ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"])141 assert not result.exception142- assert 'U:[821592c1-c50e-4971-9cd6-e89dc6832f86]' in result.output142+ assert "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]" in result.output143 144- result = runner.invoke(cli, ['--u=bar'])144+ result = runner.invoke(cli, ["--u=bar"])145 assert result.exception146- assert 'Invalid value for "--u": bar is not a valid UUID value' \147- in result.output146+ assert 'Invalid value for "--u": bar is not a valid UUID value' in result.output147 148 149 def test_float_option(runner):150 @click.command()152- @click.option('--foo', default=42, type=click.FLOAT)151+ @click.option("--foo", default=42, type=click.FLOAT)152 def cli(foo):153 assert type(foo) is float155- click.echo('FOO:[%s]' % foo)154+ click.echo("FOO:[%s]" % foo)155 156 result = runner.invoke(cli, [])157 assert not result.exception159- assert 'FOO:[42.0]' in result.output158+ assert "FOO:[42.0]" in result.output159 161- result = runner.invoke(cli, ['--foo=23.5'])160+ result = runner.invoke(cli, ["--foo=23.5"])161 assert not result.exception163- assert 'FOO:[23.5]' in result.output162+ assert "FOO:[23.5]" in result.output163 165- result = runner.invoke(cli, ['--foo=bar'])164+ result = runner.invoke(cli, ["--foo=bar"])165 assert result.exception167- assert 'Invalid value for "--foo": bar is not a valid float' \168- in result.output166+ assert 'Invalid value for "--foo": bar is not a valid float' in result.output167 168 169 def test_boolean_option(runner):170 for default in True, False:171+172 @click.command()174- @click.option('--with-foo/--without-foo', default=default)173+ @click.option("--with-foo/--without-foo", default=default)174 def cli(with_foo):175 click.echo(with_foo)176 178- result = runner.invoke(cli, ['--with-foo'])177+ result = runner.invoke(cli, ["--with-foo"])178 assert not result.exception180- assert result.output == 'True\n'181- result = runner.invoke(cli, ['--without-foo'])179+ assert result.output == "True\n"180+ result = runner.invoke(cli, ["--without-foo"])181 assert not result.exception183- assert result.output == 'False\n'182+ assert result.output == "False\n"183 result = runner.invoke(cli, [])184 assert not result.exception186- assert result.output == '%s\n' % default185+ assert result.output == "%s\n" % default186 187 for default in True, False:188+189 @click.command()190- @click.option('--flag', is_flag=True, default=default)190+ @click.option("--flag", is_flag=True, default=default)191 def cli(flag):192 click.echo(flag)193 194- result = runner.invoke(cli, ['--flag'])194+ result = runner.invoke(cli, ["--flag"])195 assert not result.exception196- assert result.output == '%s\n' % (not default)196+ assert result.output == "%s\n" % (not default)197 result = runner.invoke(cli, [])198 assert not result.exception199- assert result.output == '%s\n' % (default)199+ assert result.output == "%s\n" % (default)200 201 202 def test_boolean_conversion(runner):203 for default in True, False:204+205 @click.command()205- @click.option('--flag', default=default, type=bool)206+ @click.option("--flag", default=default, type=bool)207 def cli(flag):208 click.echo(flag)209 209- for value in 'true', 't', '1', 'yes', 'y':210- result = runner.invoke(cli, ['--flag', value])210+ for value in "true", "t", "1", "yes", "y":211+ result = runner.invoke(cli, ["--flag", value])212 assert not result.exception212- assert result.output == 'True\n'213+ assert result.output == "True\n"214 214- for value in 'false', 'f', '0', 'no', 'n':215- result = runner.invoke(cli, ['--flag', value])215+ for value in "false", "f", "0", "no", "n":216+ result = runner.invoke(cli, ["--flag", value])217 assert not result.exception217- assert result.output == 'False\n'218+ assert result.output == "False\n"219 220 result = runner.invoke(cli, [])221 assert not result.exception221- assert result.output == '%s\n' % default222+ assert result.output == "%s\n" % default223 224 225 def test_file_option(runner):226 @click.command()226- @click.option('--file', type=click.File('w'))227+ @click.option("--file", type=click.File("w"))228 def input(file):228- file.write('Hello World!\n')229+ file.write("Hello World!\n")230 231 @click.command()231- @click.option('--file', type=click.File('r'))232+ @click.option("--file", type=click.File("r"))233 def output(file):234 click.echo(file.read())235 236 with runner.isolated_filesystem():236- result_in = runner.invoke(input, ['--file=example.txt'])237- result_out = runner.invoke(output, ['--file=example.txt'])237+ result_in = runner.invoke(input, ["--file=example.txt"])238+ result_out = runner.invoke(output, ["--file=example.txt"])239 240 assert not result_in.exception240- assert result_in.output == ''241+ assert result_in.output == ""242 assert not result_out.exception242- assert result_out.output == 'Hello World!\n\n'243+ assert result_out.output == "Hello World!\n\n"244 245 246 def test_file_lazy_mode(runner):247 do_io = False248 249 @click.command()249- @click.option('--file', type=click.File('w'))250+ @click.option("--file", type=click.File("w"))251 def input(file):252 if do_io:252- file.write('Hello World!\n')253+ file.write("Hello World!\n")254 255 @click.command()255- @click.option('--file', type=click.File('r'))256+ @click.option("--file", type=click.File("r"))257 def output(file):258 pass259 260 with runner.isolated_filesystem():260- os.mkdir('example.txt')261+ os.mkdir("example.txt")262 263 do_io = True263- result_in = runner.invoke(input, ['--file=example.txt'])264+ result_in = runner.invoke(input, ["--file=example.txt"])265 assert result_in.exit_code == 1266 267 do_io = False267- result_in = runner.invoke(input, ['--file=example.txt'])268+ result_in = runner.invoke(input, ["--file=example.txt"])269 assert result_in.exit_code == 0270 270- result_out = runner.invoke(output, ['--file=example.txt'])271+ result_out = runner.invoke(output, ["--file=example.txt"])272 assert result_out.exception273 274 @click.command()274- @click.option('--file', type=click.File('w', lazy=False))275+ @click.option("--file", type=click.File("w", lazy=False))276 def input_non_lazy(file):276- file.write('Hello World!\n')277+ file.write("Hello World!\n")278 279 with runner.isolated_filesystem():279- os.mkdir('example.txt')280- result_in = runner.invoke(input_non_lazy, ['--file=example.txt'])280+ os.mkdir("example.txt")281+ result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])282 assert result_in.exit_code == 2282- assert 'Invalid value for "--file": Could not open file: example.txt' \283+ assert (284+ 'Invalid value for "--file": Could not open file: example.txt'285 in result_in.output286+ )287 288 289 def test_path_option(runner):290 @click.command()288- @click.option('-O', type=click.Path(file_okay=False, exists=True,289- writable=True))291+ @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))292 def write_to_dir(o):291- with open(os.path.join(o, 'foo.txt'), 'wb') as f:292- f.write(b'meh\n')293+ with open(os.path.join(o, "foo.txt"), "wb") as f:294+ f.write(b"meh\n")295 296 with runner.isolated_filesystem():295- os.mkdir('test')297+ os.mkdir("test")298 297- result = runner.invoke(write_to_dir, ['-O', 'test'])299+ result = runner.invoke(write_to_dir, ["-O", "test"])300 assert not result.exception301 300- with open('test/foo.txt', 'rb') as f:301- assert f.read() == b'meh\n'302+ with open("test/foo.txt", "rb") as f:303+ assert f.read() == b"meh\n"304 303- result = runner.invoke(write_to_dir, ['-O', 'test/foo.txt'])304- assert 'Invalid value for "-O": Directory "test/foo.txt" is a file.' \305+ result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])306+ assert (307+ 'Invalid value for "-O": Directory "test/foo.txt" is a file.'308 in result.output309+ )310 311 @click.command()308- @click.option('-f', type=click.Path(exists=True))312+ @click.option("-f", type=click.Path(exists=True))313 def showtype(f):310- click.echo('is_file=%s' % os.path.isfile(f))311- click.echo('is_dir=%s' % os.path.isdir(f))314+ click.echo("is_file=%s" % os.path.isfile(f))315+ click.echo("is_dir=%s" % os.path.isdir(f))316 317 with runner.isolated_filesystem():314- result = runner.invoke(showtype, ['-f', 'xxx'])315- assert 'Error: Invalid value for "-f": Path "xxx" does not exist' \316- in result.output318+ result = runner.invoke(showtype, ["-f", "xxx"])319+ assert (320+ 'Error: Invalid value for "-f": Path "xxx" does not exist' in result.output321+ )322 318- result = runner.invoke(showtype, ['-f', '.'])319- assert 'is_file=False' in result.output320- assert 'is_dir=True' in result.output323+ result = runner.invoke(showtype, ["-f", "."])324+ assert "is_file=False" in result.output325+ assert "is_dir=True" in result.output326 327 @click.command()323- @click.option('-f', type=click.Path())328+ @click.option("-f", type=click.Path())329 def exists(f):325- click.echo('exists=%s' % os.path.exists(f))330+ click.echo("exists=%s" % os.path.exists(f))331 332 with runner.isolated_filesystem():328- result = runner.invoke(exists, ['-f', 'xxx'])329- assert 'exists=False' in result.output333+ result = runner.invoke(exists, ["-f", "xxx"])334+ assert "exists=False" in result.output335 331- result = runner.invoke(exists, ['-f', '.'])332- assert 'exists=True' in result.output336+ result = runner.invoke(exists, ["-f", "."])337+ assert "exists=True" in result.output338 339 340 def test_choice_option(runner):341 @click.command()337- @click.option('--method', type=click.Choice(['foo', 'bar', 'baz']))342+ @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))343 def cli(method):344 click.echo(method)345 341- result = runner.invoke(cli, ['--method=foo'])346+ result = runner.invoke(cli, ["--method=foo"])347 assert not result.exception343- assert result.output == 'foo\n'348+ assert result.output == "foo\n"349 345- result = runner.invoke(cli, ['--method=meh'])350+ result = runner.invoke(cli, ["--method=meh"])351 assert result.exit_code == 2347- assert 'Invalid value for "--method": invalid choice: meh. ' \348- '(choose from foo, bar, baz)' in result.output352+ assert (353+ 'Invalid value for "--method": invalid choice: meh. '354+ "(choose from foo, bar, baz)" in result.output355+ )356 350- result = runner.invoke(cli, ['--help'])351- assert '--method [foo|bar|baz]' in result.output357+ result = runner.invoke(cli, ["--help"])358+ assert "--method [foo|bar|baz]" in result.output359 360 361 def test_datetime_option_default(runner):355-362 @click.command()357- @click.option('--start_date', type=click.DateTime())363+ @click.option("--start_date", type=click.DateTime())364 def cli(start_date):359- click.echo(start_date.strftime('%Y-%m-%dT%H:%M:%S'))365+ click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))366 361- result = runner.invoke(cli, ['--start_date=2015-09-29'])367+ result = runner.invoke(cli, ["--start_date=2015-09-29"])368 assert not result.exception363- assert result.output == '2015-09-29T00:00:00\n'369+ assert result.output == "2015-09-29T00:00:00\n"370 365- result = runner.invoke(cli, ['--start_date=2015-09-29T09:11:22'])371+ result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])372 assert not result.exception367- assert result.output == '2015-09-29T09:11:22\n'373+ assert result.output == "2015-09-29T09:11:22\n"374 369- result = runner.invoke(cli, ['--start_date=2015-09'])375+ result = runner.invoke(cli, ["--start_date=2015-09"])376 assert result.exit_code == 2371- assert ('Invalid value for "--start_date": '372- 'invalid datetime format: 2015-09. '373- '(choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)'374- ) in result.output377+ assert (378+ 'Invalid value for "--start_date": '379+ "invalid datetime format: 2015-09. "380+ "(choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"381+ ) in result.output382 376- result = runner.invoke(cli, ['--help'])377- assert '--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]' in result.output383+ result = runner.invoke(cli, ["--help"])384+ assert (385+ "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output386+ )387 388 389 def test_datetime_option_custom(runner):390 @click.command()382- @click.option('--start_date',383- type=click.DateTime(formats=['%A %B %d, %Y']))391+ @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))392 def cli(start_date):385- click.echo(start_date.strftime('%Y-%m-%dT%H:%M:%S'))393+ click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))394 387- result = runner.invoke(cli, ['--start_date=Wednesday June 05, 2010'])395+ result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])396 assert not result.exception389- assert result.output == '2010-06-05T00:00:00\n'397+ assert result.output == "2010-06-05T00:00:00\n"398 399 400 def test_int_range_option(runner):401 @click.command()394- @click.option('--x', type=click.IntRange(0, 5))402+ @click.option("--x", type=click.IntRange(0, 5))403 def cli(x):404 click.echo(x)405 398- result = runner.invoke(cli, ['--x=5'])406+ result = runner.invoke(cli, ["--x=5"])407 assert not result.exception400- assert result.output == '5\n'408+ assert result.output == "5\n"409 402- result = runner.invoke(cli, ['--x=6'])410+ result = runner.invoke(cli, ["--x=6"])411 assert result.exit_code == 2404- assert 'Invalid value for "--x": 6 is not in the valid range of 0 to 5.\n' \412+ assert (413+ 'Invalid value for "--x": 6 is not in the valid range of 0 to 5.\n'414 in result.output415+ )416 417 @click.command()408- @click.option('--x', type=click.IntRange(0, 5, clamp=True))418+ @click.option("--x", type=click.IntRange(0, 5, clamp=True))419 def clamp(x):420 click.echo(x)421 412- result = runner.invoke(clamp, ['--x=5'])422+ result = runner.invoke(clamp, ["--x=5"])423 assert not result.exception414- assert result.output == '5\n'424+ assert result.output == "5\n"425 416- result = runner.invoke(clamp, ['--x=6'])426+ result = runner.invoke(clamp, ["--x=6"])427 assert not result.exception418- assert result.output == '5\n'428+ assert result.output == "5\n"429 420- result = runner.invoke(clamp, ['--x=-1'])430+ result = runner.invoke(clamp, ["--x=-1"])431 assert not result.exception422- assert result.output == '0\n'432+ assert result.output == "0\n"433 434 435 def test_float_range_option(runner):436 @click.command()427- @click.option('--x', type=click.FloatRange(0, 5))437+ @click.option("--x", type=click.FloatRange(0, 5))438 def cli(x):439 click.echo(x)440 431- result = runner.invoke(cli, ['--x=5.0'])441+ result = runner.invoke(cli, ["--x=5.0"])442 assert not result.exception433- assert result.output == '5.0\n'443+ assert result.output == "5.0\n"444 435- result = runner.invoke(cli, ['--x=6.0'])445+ result = runner.invoke(cli, ["--x=6.0"])446 assert result.exit_code == 2437- assert 'Invalid value for "--x": 6.0 is not in the valid range of 0 to 5.\n' \447+ assert (448+ 'Invalid value for "--x": 6.0 is not in the valid range of 0 to 5.\n'449 in result.output450+ )451 452 @click.command()441- @click.option('--x', type=click.FloatRange(0, 5, clamp=True))453+ @click.option("--x", type=click.FloatRange(0, 5, clamp=True))454 def clamp(x):455 click.echo(x)456 445- result = runner.invoke(clamp, ['--x=5.0'])457+ result = runner.invoke(clamp, ["--x=5.0"])458 assert not result.exception447- assert result.output == '5.0\n'459+ assert result.output == "5.0\n"460 449- result = runner.invoke(clamp, ['--x=6.0'])461+ result = runner.invoke(clamp, ["--x=6.0"])462 assert not result.exception451- assert result.output == '5\n'463+ assert result.output == "5\n"464 453- result = runner.invoke(clamp, ['--x=-1.0'])465+ result = runner.invoke(clamp, ["--x=-1.0"])466 assert not result.exception455- assert result.output == '0\n'467+ assert result.output == "0\n"468 469 470 def test_required_option(runner):471 @click.command()460- @click.option('--foo', required=True)472+ @click.option("--foo", required=True)473 def cli(foo):474 click.echo(foo)475 476 result = runner.invoke(cli, [])8 unmodified lines485 called.append(value)486 return value487 488 @click.command()477- @click.option('--missing', default='missing',478- is_eager=False, callback=memo)479- @click.option('--eager-flag1', flag_value='eager1',480- is_eager=True, callback=memo)481- @click.option('--eager-flag2', flag_value='eager2',482- is_eager=True, callback=memo)483- @click.option('--eager-flag3', flag_value='eager3',484- is_eager=True, callback=memo)485- @click.option('--normal-flag1', flag_value='normal1',486- is_eager=False, callback=memo)487- @click.option('--normal-flag2', flag_value='normal2',488- is_eager=False, callback=memo)489- @click.option('--normal-flag3', flag_value='normal3',490- is_eager=False, callback=memo)489+ @click.option("--missing", default="missing", is_eager=False, callback=memo)490+ @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)491+ @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)492+ @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)493+ @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)494+ @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)495+ @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)496 def cli(**x):497 pass498 494- result = runner.invoke(cli, ['--eager-flag2',495- '--eager-flag1',496- '--normal-flag2',497- '--eager-flag3',498- '--normal-flag3',499- '--normal-flag3',500- '--normal-flag1',501- '--normal-flag1'])499+ result = runner.invoke(500+ cli,501+ [502+ "--eager-flag2",503+ "--eager-flag1",504+ "--normal-flag2",505+ "--eager-flag3",506+ "--normal-flag3",507+ "--normal-flag3",508+ "--normal-flag1",509+ "--normal-flag1",510+ ],511+ )512 assert not result.exception513 assert called == [504- 'eager2',505- 'eager1',506- 'eager3',507- 'normal2',508- 'normal3',509- 'normal1',510- 'missing',514+ "eager2",515+ "eager1",516+ "eager3",517+ "normal2",518+ "normal3",519+ "normal1",520+ "missing",521 ]522 523 524 def test_hidden_option(runner):525 @click.command()516- @click.option('--nope', hidden=True)526+ @click.option("--nope", hidden=True)527 def cli(nope):528 click.echo(nope)529 520- result = runner.invoke(cli, ['--help'])530+ result = runner.invoke(cli, ["--help"])531 assert result.exit_code == 0522- assert '--nope' not in result.output532+ assert "--nope" not in result.output533 534 535 def test_hidden_command(runner):536 @click.group()3 unmodified lines540 @cli.command(hidden=True)541 def nope():542 pass543 534- result = runner.invoke(cli, ['--help'])544+ result = runner.invoke(cli, ["--help"])545 assert result.exit_code == 0536- assert 'nope' not in result.output546+ assert "nope" not in result.output547 548 549 def test_hidden_group(runner):550 @click.group()7 unmodified lines558 @subgroup.command()559 def nope():560 pass561 552- result = runner.invoke(cli, ['--help'])562+ result = runner.invoke(cli, ["--help"])563 assert result.exit_code == 0554- assert 'subgroup' not in result.output555- assert 'nope' not in result.output564+ assert "subgroup" not in result.output565+ assert "nope" not in result.outputmodified:tests/test_chain.py+78 added-75 removed
4 unmodified lines5 import click6 7 8 def debug():9- click.echo('%s=%s' % (10- sys._getframe(1).f_code.co_name,11- '|'.join(click.get_current_context().args),12- ))9+ click.echo(10+ "%s=%s"11+ % (sys._getframe(1).f_code.co_name, "|".join(click.get_current_context().args),)12+ )13 14 15 def test_basic_chaining(runner):16 @click.group(chain=True)17 def cli():18 pass19 20- @cli.command('sdist')20+ @cli.command("sdist")21 def sdist():22- click.echo('sdist called')22+ click.echo("sdist called")23 24- @cli.command('bdist')24+ @cli.command("bdist")25 def bdist():26- click.echo('bdist called')26+ click.echo("bdist called")27 28- result = runner.invoke(cli, ['bdist', 'sdist', 'bdist'])28+ result = runner.invoke(cli, ["bdist", "sdist", "bdist"])29 assert not result.exception30 assert result.output.splitlines() == [31- 'bdist called',32- 'sdist called',33- 'bdist called',31+ "bdist called",32+ "sdist called",33+ "bdist called",34 ]35 36 37 def test_chaining_help(runner):1 unmodified line39 def cli():40 """ROOT HELP"""41 pass42 43- @cli.command('sdist')43+ @cli.command("sdist")44 def sdist():45 """SDIST HELP"""46- click.echo('sdist called')46+ click.echo("sdist called")47 48- @cli.command('bdist')48+ @cli.command("bdist")49 def bdist():50 """BDIST HELP"""51- click.echo('bdist called')51+ click.echo("bdist called")52 53- result = runner.invoke(cli, ['--help'])53+ result = runner.invoke(cli, ["--help"])54 assert not result.exception55- assert 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...' in result.output56- assert 'ROOT HELP' in result.output55+ assert "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." in result.output56+ assert "ROOT HELP" in result.output57 58- result = runner.invoke(cli, ['sdist', '--help'])58+ result = runner.invoke(cli, ["sdist", "--help"])59 assert not result.exception60- assert 'SDIST HELP' in result.output60+ assert "SDIST HELP" in result.output61 62- result = runner.invoke(cli, ['bdist', '--help'])62+ result = runner.invoke(cli, ["bdist", "--help"])63 assert not result.exception64- assert 'BDIST HELP' in result.output64+ assert "BDIST HELP" in result.output65 66- result = runner.invoke(cli, ['bdist', 'sdist', '--help'])66+ result = runner.invoke(cli, ["bdist", "sdist", "--help"])67 assert not result.exception68- assert 'SDIST HELP' in result.output68+ assert "SDIST HELP" in result.output69 70 71 def test_chaining_with_options(runner):72 @click.group(chain=True)73 def cli():74 pass75 76- @cli.command('sdist')77- @click.option('--format')76+ @cli.command("sdist")77+ @click.option("--format")78 def sdist(format):79- click.echo('sdist called %s' % format)79+ click.echo("sdist called %s" % format)80 81- @cli.command('bdist')82- @click.option('--format')81+ @cli.command("bdist")82+ @click.option("--format")83 def bdist(format):84- click.echo('bdist called %s' % format)84+ click.echo("bdist called %s" % format)85 86- result = runner.invoke(cli, ['bdist', '--format=1', 'sdist', '--format=2'])86+ result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"])87 assert not result.exception88 assert result.output.splitlines() == [89- 'bdist called 1',90- 'sdist called 2',89+ "bdist called 1",90+ "sdist called 2",91 ]92 93 94 def test_chaining_with_arguments(runner):95 @click.group(chain=True)96 def cli():97 pass98 99- @cli.command('sdist')100- @click.argument('format')99+ @cli.command("sdist")100+ @click.argument("format")101 def sdist(format):102- click.echo('sdist called %s' % format)102+ click.echo("sdist called %s" % format)103 104- @cli.command('bdist')105- @click.argument('format')104+ @cli.command("bdist")105+ @click.argument("format")106 def bdist(format):107- click.echo('bdist called %s' % format)107+ click.echo("bdist called %s" % format)108 109- result = runner.invoke(cli, ['bdist', '1', 'sdist', '2'])109+ result = runner.invoke(cli, ["bdist", "1", "sdist", "2"])110 assert not result.exception111 assert result.output.splitlines() == [112- 'bdist called 1',113- 'sdist called 2',112+ "bdist called 1",113+ "sdist called 2",114 ]115 116 117 def test_pipeline(runner):118 @click.group(chain=True, invoke_without_command=True)119- @click.option('-i', '--input', type=click.File('r'))119+ @click.option("-i", "--input", type=click.File("r"))120 def cli(input):121 pass122 123 @cli.resultcallback()124 def process_pipeline(processors, input):125- iterator = (x.rstrip('\r\n') for x in input)125+ iterator = (x.rstrip("\r\n") for x in input)126 for processor in processors:127 iterator = processor(iterator)128 for item in iterator:129 click.echo(item)130 131- @cli.command('uppercase')131+ @cli.command("uppercase")132 def make_uppercase():133 def processor(iterator):134 for line in iterator:135 yield line.upper()136+137 return processor138 138- @cli.command('strip')139+ @cli.command("strip")140 def make_strip():141 def processor(iterator):142 for line in iterator:143 yield line.strip()144+145 return processor146 145- result = runner.invoke(cli, ['-i', '-'], input='foo\nbar')147+ result = runner.invoke(cli, ["-i", "-"], input="foo\nbar")148 assert not result.exception149 assert result.output.splitlines() == [148- 'foo',149- 'bar',150+ "foo",151+ "bar",152 ]153 152- result = runner.invoke(cli, ['-i', '-', 'strip'], input='foo \n bar')154+ result = runner.invoke(cli, ["-i", "-", "strip"], input="foo \n bar")155 assert not result.exception156 assert result.output.splitlines() == [155- 'foo',156- 'bar',157+ "foo",158+ "bar",159 ]160 159- result = runner.invoke(cli, ['-i', '-', 'strip', 'uppercase'],160- input='foo \n bar')161+ result = runner.invoke(cli, ["-i", "-", "strip", "uppercase"], input="foo \n bar")162 assert not result.exception163 assert result.output.splitlines() == [163- 'FOO',164- 'BAR',164+ "FOO",165+ "BAR",166 ]167 168 169 def test_args_and_chain(runner):12 unmodified lines182 @cli.command()183 def c():184 debug()185 185- result = runner.invoke(cli, ['a', 'b', 'c'])186+ result = runner.invoke(cli, ["a", "b", "c"])187 assert not result.exception188 assert result.output.splitlines() == [188- 'cli=',189- 'a=',190- 'b=',191- 'c=',189+ "cli=",190+ "a=",191+ "b=",192+ "c=",193 ]194 195 196 def test_multicommand_arg_behavior(runner):197 with pytest.raises(RuntimeError):198+199 @click.group(chain=True)198- @click.argument('forbidden', required=False)200+ @click.argument("forbidden", required=False)201 def bad_cli():202 pass203 204 with pytest.raises(RuntimeError):205+206 @click.group(chain=True)204- @click.argument('forbidden', nargs=-1)207+ @click.argument("forbidden", nargs=-1)208 def bad_cli2():209 pass210 211 @click.group(chain=True)209- @click.argument('arg')212+ @click.argument("arg")213 def cli(arg):211- click.echo('cli:%s' % arg)214+ click.echo("cli:%s" % arg)215 216 @cli.command()217 def a():215- click.echo('a')218+ click.echo("a")219 217- result = runner.invoke(cli, ['foo', 'a'])220+ result = runner.invoke(cli, ["foo", "a"])221 assert not result.exception222 assert result.output.splitlines() == [220- 'cli:foo',221- 'a',223+ "cli:foo",224+ "a",225 ]226 227 228 @pytest.mark.xfail17 unmodified lines246 @cli.command()247 def l1b():248 debug()249 247- result = runner.invoke(cli, ['l1a', 'l2a', 'l1b'])250+ result = runner.invoke(cli, ["l1a", "l2a", "l1b"])251 assert not result.exception252 assert result.output.splitlines() == [250- 'cli=',251- 'l1a=',252- 'l2a=',253- 'l1b=',253+ "cli=",254+ "l1a=",255+ "l2a=",256+ "l1b=",257 ]modified:tests/test_commands.py+88 added-80 removed
9 unmodified lines10 def cli(ctx):11 return ctx.invoke(other_cmd, arg=42)12 13 @click.command()14- @click.argument('arg', type=click.INT)14+ @click.argument("arg", type=click.INT)15 def other_cmd(arg):16 click.echo(arg)17 18 result = runner.invoke(cli, [])19 assert not result.exception20- assert result.output == '42\n'20+ assert result.output == "42\n"21 22 23 def test_other_command_forward(runner):24 cli = click.Group()25 26 @cli.command()27- @click.option('--count', default=1)27+ @click.option("--count", default=1)28 def test(count):29- click.echo('Count: %d' % count)29+ click.echo("Count: %d" % count)30 31 @cli.command()32- @click.option('--count', default=1)32+ @click.option("--count", default=1)33 @click.pass_context34 def dist(ctx, count):35 ctx.forward(test)36 ctx.invoke(test, count=42)37 38- result = runner.invoke(cli, ['dist'])38+ result = runner.invoke(cli, ["dist"])39 assert not result.exception40- assert result.output == 'Count: 1\nCount: 42\n'40+ assert result.output == "Count: 1\nCount: 42\n"41 42 43 def test_auto_shorthelp(runner):44 @click.group()12 unmodified lines57 def long():58 """This is a long text that is too long to show as short help59 and will be truncated instead."""60 61- result = runner.invoke(cli, ['--help'])62- assert re.search(63- r'Commands:\n\s+'64- r'long\s+This is a long text that is too long to show as short help\.\.\.\n\s+'65- r'short\s+This is a short text\.\n\s+'66- r'special-chars\s+Login and store the token in ~/.netrc\.\s*',67- result.output) is not None61+ result = runner.invoke(cli, ["--help"])62+ assert (63+ re.search(64+ r"Commands:\n\s+"65+ r"long\s+This is a long text that is too long to show as short help\.\.\.\n\s+"66+ r"short\s+This is a short text\.\n\s+"67+ r"special-chars\s+Login and store the token in ~/.netrc\.\s*",68+ result.output,69+ )70+ is not None71+ )72 73 74 def test_no_args_is_help(runner):75 @click.command(no_args_is_help=True)1 unmodified line77 pass78 79 result = runner.invoke(cli, [])80 assert result.exit_code == 077- assert 'Show this message and exit.' in result.output81+ assert "Show this message and exit." in result.output82 83 84 def test_default_maps(runner):85 @click.group()86 def cli():87 pass88 89 @cli.command()86- @click.option('--name', default='normal')90+ @click.option("--name", default="normal")91 def foo(name):92 click.echo(name)93 90- result = runner.invoke(cli, ['foo'], default_map={91- 'foo': {'name': 'changed'}92- })94+ result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})95 96 assert not result.exception95- assert result.output == 'changed\n'97+ assert result.output == "changed\n"98 99 100 def test_group_with_args(runner):101 @click.group()100- @click.argument('obj')102+ @click.argument("obj")103 def cli(obj):102- click.echo('obj=%s' % obj)104+ click.echo("obj=%s" % obj)105 106 @cli.command()107 def move():106- click.echo('move')108+ click.echo("move")109 110 result = runner.invoke(cli, [])111 assert result.exit_code == 0110- assert 'Show this message and exit.' in result.output112+ assert "Show this message and exit." in result.output113 112- result = runner.invoke(cli, ['obj1'])114+ result = runner.invoke(cli, ["obj1"])115 assert result.exit_code == 2114- assert 'Error: Missing command.' in result.output116+ assert "Error: Missing command." in result.output117 116- result = runner.invoke(cli, ['obj1', '--help'])118+ result = runner.invoke(cli, ["obj1", "--help"])119 assert result.exit_code == 0118- assert 'Show this message and exit.' in result.output120+ assert "Show this message and exit." in result.output121 120- result = runner.invoke(cli, ['obj1', 'move'])122+ result = runner.invoke(cli, ["obj1", "move"])123 assert result.exit_code == 0122- assert result.output == 'obj=obj1\nmove\n'124+ assert result.output == "obj=obj1\nmove\n"125 126 127 def test_base_command(runner):128 import optparse2 unmodified lines131 def cli():132 pass133 134 class OptParseCommand(click.BaseCommand):133-135 def __init__(self, name, parser, callback):136 click.BaseCommand.__init__(self, name)137 self.parser = parser138 self.callback = callback14 unmodified lines153 154 def invoke(self, ctx):155 ctx.invoke(self.callback, ctx.args, **ctx.params)156 156- parser = optparse.OptionParser(usage='Usage: foo test [OPTIONS]')157- parser.add_option("-f", "--file", dest="filename",158- help="write report to FILE", metavar="FILE")159- parser.add_option("-q", "--quiet",160- action="store_false", dest="verbose", default=True,161- help="don't print status messages to stdout")157+ parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]")158+ parser.add_option(159+ "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE"160+ )161+ parser.add_option(162+ "-q",163+ "--quiet",164+ action="store_false",165+ dest="verbose",166+ default=True,167+ help="don't print status messages to stdout",168+ )169 170 def test_callback(args, filename, verbose):164- click.echo(' '.join(args))171+ click.echo(" ".join(args))172 click.echo(filename)173 click.echo(verbose)167- cli.add_command(OptParseCommand('test', parser, test_callback))174 169- result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',170- 'whatever.txt', 'whateverelse.txt'])175+ cli.add_command(OptParseCommand("test", parser, test_callback))176+177+ result = runner.invoke(178+ cli, ["test", "-f", "test.txt", "-q", "whatever.txt", "whateverelse.txt"]179+ )180 assert not result.exception181 assert result.output.splitlines() == [173- 'whatever.txt whateverelse.txt',174- 'test.txt',175- 'False',182+ "whatever.txt whateverelse.txt",183+ "test.txt",184+ "False",185 ]186 178- result = runner.invoke(cli, ['test', '--help'])187+ result = runner.invoke(cli, ["test", "--help"])188 assert not result.exception189 assert result.output.splitlines() == [181- 'Usage: foo test [OPTIONS]',182- '',183- 'Options:',184- ' -h, --help show this help message and exit',185- ' -f FILE, --file=FILE write report to FILE',186- ' -q, --quiet don\'t print status messages to stdout',190+ "Usage: foo test [OPTIONS]",191+ "",192+ "Options:",193+ " -h, --help show this help message and exit",194+ " -f FILE, --file=FILE write report to FILE",195+ " -q, --quiet don't print status messages to stdout",196 ]197 198 199 def test_object_propagation(runner):200 for chain in False, True:201+202 @click.group(chain=chain)193- @click.option('--debug/--no-debug', default=False)203+ @click.option("--debug/--no-debug", default=False)204 @click.pass_context205 def cli(ctx, debug):206 if ctx.obj is None:207 ctx.obj = {}198- ctx.obj['DEBUG'] = debug208+ ctx.obj["DEBUG"] = debug209 210 @cli.command()211 @click.pass_context212 def sync(ctx):203- click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))213+ click.echo("Debug is %s" % (ctx.obj["DEBUG"] and "on" or "off"))214 205- result = runner.invoke(cli, ['sync'])215+ result = runner.invoke(cli, ["sync"])216 assert result.exception is None207- assert result.output == 'Debug is off\n'217+ assert result.output == "Debug is off\n"218 219 220 def test_other_command_invoke_with_defaults(runner):221 @click.command()1 unmodified line223 def cli(ctx):224 return ctx.invoke(other_cmd)225 226 @click.command()217- @click.option('--foo', type=click.INT, default=42)227+ @click.option("--foo", type=click.INT, default=42)228 @click.pass_context229 def other_cmd(ctx, foo):220- assert ctx.info_name == 'other-cmd'230+ assert ctx.info_name == "other-cmd"231 click.echo(foo)232 233 result = runner.invoke(cli, [])234 assert not result.exception225- assert result.output == '42\n'235+ assert result.output == "42\n"236 237 238 def test_invoked_subcommand(runner):239 @click.group(invoke_without_command=True)240 @click.pass_context241 def cli(ctx):242 if ctx.invoked_subcommand is None:233- click.echo('no subcommand, use default')243+ click.echo("no subcommand, use default")244 ctx.invoke(sync)245 else:236- click.echo('invoke subcommand')246+ click.echo("invoke subcommand")247 248 @cli.command()249 def sync():240- click.echo('in subcommand')250+ click.echo("in subcommand")251 242- result = runner.invoke(cli, ['sync'])252+ result = runner.invoke(cli, ["sync"])253 assert not result.exception244- assert result.output == 'invoke subcommand\nin subcommand\n'254+ assert result.output == "invoke subcommand\nin subcommand\n"255 256 result = runner.invoke(cli)257 assert not result.exception248- assert result.output == 'no subcommand, use default\nin subcommand\n'258+ assert result.output == "no subcommand, use default\nin subcommand\n"259 260 261 def test_unprocessed_options(runner):252- @click.command(context_settings=dict(253- ignore_unknown_options=True254- ))255- @click.argument('args', nargs=-1, type=click.UNPROCESSED)256- @click.option('--verbose', '-v', count=True)262+ @click.command(context_settings=dict(ignore_unknown_options=True))263+ @click.argument("args", nargs=-1, type=click.UNPROCESSED)264+ @click.option("--verbose", "-v", count=True)265 def cli(verbose, args):258- click.echo('Verbosity: %s' % verbose)259- click.echo('Args: %s' % '|'.join(args))266+ click.echo("Verbosity: %s" % verbose)267+ click.echo("Args: %s" % "|".join(args))268 261- result = runner.invoke(cli, ['-foo', '-vvvvx', '--muhaha', 'x', 'y', '-x'])269+ result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])270 assert not result.exception271 assert result.output.splitlines() == [264- 'Verbosity: 4',265- 'Args: -foo|-x|--muhaha|x|y|-x',272+ "Verbosity: 4",273+ "Args: -foo|-x|--muhaha|x|y|-x",274 ]275 276 277 def test_deprecated_in_help_messages(runner):1 unmodified line279 def cmd_with_help():280 """CLI HELP"""281 pass282 275- result = runner.invoke(cmd_with_help, ['--help'])276- assert '(DEPRECATED)' in result.output283+ result = runner.invoke(cmd_with_help, ["--help"])284+ assert "(DEPRECATED)" in result.output285 286 @click.command(deprecated=True)287 def cmd_without_help():288 pass289 282- result = runner.invoke(cmd_without_help, ['--help'])283- assert '(DEPRECATED)' in result.output290+ result = runner.invoke(cmd_without_help, ["--help"])291+ assert "(DEPRECATED)" in result.output292 293 294 def test_deprecated_in_invocation(runner):295 @click.command(deprecated=True)296 def deprecated_cmd():297 debug()298 299 result = runner.invoke(deprecated_cmd)292- assert 'DeprecationWarning:' in result.output300+ assert "DeprecationWarning:" in result.outputmodified:tests/test_compat.py+13 added-11 removed
8 unmodified lines9 def legacy_callback(ctx, value):10 return value.upper()11 12 @click.command()13- @click.option('--foo', callback=legacy_callback)13+ @click.option("--foo", callback=legacy_callback)14 def cli(foo):15 click.echo(foo)16 17- with pytest.warns(Warning, match='Invoked legacy parameter callback'):18- result = runner.invoke(cli, ['--foo', 'wat'])17+ with pytest.warns(Warning, match="Invoked legacy parameter callback"):18+ result = runner.invoke(cli, ["--foo", "wat"])19 assert result.exit_code == 020- assert 'WAT' in result.output20+ assert "WAT" in result.output21 22 23 def test_bash_func_name():24 from click._bashcomplete import get_completion_script25- script = get_completion_script('foo-bar baz_blah', '_COMPLETE_VAR', 'bash').strip()26- assert script.startswith('_foo_barbaz_blah_completion()')27- assert '_COMPLETE_VAR=complete $1' in script25 26+ script = get_completion_script("foo-bar baz_blah", "_COMPLETE_VAR", "bash").strip()27+ assert script.startswith("_foo_barbaz_blah_completion()")28+ assert "_COMPLETE_VAR=complete $1" in script29 30+31 def test_zsh_func_name():32 from click._bashcomplete import get_completion_script32- script = get_completion_script('foo-bar', '_COMPLETE_VAR', 'zsh').strip()33- assert script.startswith('#compdef foo-bar')34- assert 'compdef _foo_bar_completion foo-bar;' in script35- assert '(( ! $+commands[foo-bar] )) && return 1' in script33 34+ script = get_completion_script("foo-bar", "_COMPLETE_VAR", "zsh").strip()35+ assert script.startswith("#compdef foo-bar")36+ assert "compdef _foo_bar_completion foo-bar;" in script37+ assert "(( ! $+commands[foo-bar] )) && return 1" in script38 39+40 @pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")41 def test_is_jupyter_kernel_output():42 class JupyterKernelFakeStream(object):43 pass4 unmodified linesmodified:tests/test_context.py+39 added-34 removed
3 unmodified lines4 5 def test_ensure_context_objects(runner):6 class Foo(object):7 def __init__(self):8- self.title = 'default'8+ self.title = "default"9 10 pass_foo = click.make_pass_decorator(Foo, ensure=True)11 12 @click.group()5 unmodified lines18 @pass_foo19 def test(foo):20 click.echo(foo.title)21 22- result = runner.invoke(cli, ['test'])22+ result = runner.invoke(cli, ["test"])23 assert not result.exception24- assert result.output == 'default\n'24+ assert result.output == "default\n"25 26 27 def test_get_context_objects(runner):28 class Foo(object):29 def __init__(self):30- self.title = 'default'30+ self.title = "default"31 32 pass_foo = click.make_pass_decorator(Foo, ensure=True)33 34 @click.group()35 @click.pass_context36 def cli(ctx):37 ctx.obj = Foo()38- ctx.obj.title = 'test'38+ ctx.obj.title = "test"39 40 @cli.command()41 @pass_foo42 def test(foo):43 click.echo(foo.title)44 45- result = runner.invoke(cli, ['test'])45+ result = runner.invoke(cli, ["test"])46 assert not result.exception47- assert result.output == 'test\n'47+ assert result.output == "test\n"48 49 50 def test_get_context_objects_no_ensuring(runner):51 class Foo(object):52 def __init__(self):53- self.title = 'default'53+ self.title = "default"54 55 pass_foo = click.make_pass_decorator(Foo)56 57 @click.group()58 @click.pass_context59 def cli(ctx):60 ctx.obj = Foo()61- ctx.obj.title = 'test'61+ ctx.obj.title = "test"62 63 @cli.command()64 @pass_foo65 def test(foo):66 click.echo(foo.title)67 68- result = runner.invoke(cli, ['test'])68+ result = runner.invoke(cli, ["test"])69 assert not result.exception70- assert result.output == 'test\n'70+ assert result.output == "test\n"71 72 73 def test_get_context_objects_missing(runner):74 class Foo(object):10 unmodified lines85 @pass_foo86 def test(foo):87 click.echo(foo.title)88 89- result = runner.invoke(cli, ['test'])89+ result = runner.invoke(cli, ["test"])90 assert result.exception is not None91 assert isinstance(result.exception, RuntimeError)92- assert "Managed to invoke callback without a context object " \92+ assert (93+ "Managed to invoke callback without a context object "94 "of type 'Foo' existing" in str(result.exception)95+ )96 97 98 def test_multi_enter(runner):99 called = []2 unmodified lines102 @click.pass_context103 def cli(ctx):104 def callback():105 called.append(True)106+107 ctx.call_on_close(callback)108 109 with ctx:110 pass8 unmodified lines119 @click.command()120 @click.pass_context121 def cli(ctx):122 assert click.get_current_context() is ctx120- ctx.obj = 'FOOBAR'121- assert click.get_current_context().obj == 'FOOBAR'123+ ctx.obj = "FOOBAR"124+ assert click.get_current_context().obj == "FOOBAR"125 126 assert click.get_current_context(silent=True) is None127 runner.invoke(cli, [], catch_exceptions=False)128 assert click.get_current_context(silent=True) is None129 130 131 def test_context_meta(runner):129- LANG_KEY = __name__ + '.lang'132+ LANG_KEY = __name__ + ".lang"133 134 def set_language(value):135 click.get_current_context().meta[LANG_KEY] = value136 137 def get_language():135- return click.get_current_context().meta.get(LANG_KEY, 'en_US')138+ return click.get_current_context().meta.get(LANG_KEY, "en_US")139 140 @click.command()141 @click.pass_context142 def cli(ctx):140- assert get_language() == 'en_US'141- set_language('de_DE')142- assert get_language() == 'de_DE'143+ assert get_language() == "en_US"144+ set_language("de_DE")145+ assert get_language() == "de_DE"146 147 runner.invoke(cli, [], catch_exceptions=False)148 149 26 unmodified lines176 def test_pass_obj(runner):177 @click.group()178 @click.pass_context179 def cli(ctx):177- ctx.obj = 'test'180+ ctx.obj = "test"181 182 @cli.command()183 @click.pass_obj184 def test(obj):185 click.echo(obj)186 184- result = runner.invoke(cli, ['test'])187+ result = runner.invoke(cli, ["test"])188 assert not result.exception186- assert result.output == 'test\n'189+ assert result.output == "test\n"190 191 192 def test_close_before_pop(runner):193 called = []194 195 @click.command()196 @click.pass_context197 def cli(ctx):195- ctx.obj = 'test'198+ ctx.obj = "test"199 200 @ctx.call_on_close201 def foo():199- assert click.get_current_context().obj == 'test'202+ assert click.get_current_context().obj == "test"203 called.append(True)201- click.echo('aha!')204 205+ click.echo("aha!")206+207 result = runner.invoke(cli, [])208 assert not result.exception205- assert result.output == 'aha!\n'209+ assert result.output == "aha!\n"210 assert called == [True]211 212 213 def test_make_pass_decorator_args(runner):214 """215 Test to check that make_pass_decorator doesn't consume arguments based on216 invocation order.217 """218+219 class Foo(object):215- title = 'foocmd'220+ title = "foocmd"221 222 pass_foo = click.make_pass_decorator(Foo)223 224 @click.group()12 unmodified lines237 @click.pass_context238 def test2(ctx, foo):239 click.echo(foo.title)240 236- result = runner.invoke(cli, ['test1'])241+ result = runner.invoke(cli, ["test1"])242 assert not result.exception238- assert result.output == 'foocmd\n'243+ assert result.output == "foocmd\n"244 240- result = runner.invoke(cli, ['test2'])245+ result = runner.invoke(cli, ["test2"])246 assert not result.exception242- assert result.output == 'foocmd\n'247+ assert result.output == "foocmd\n"248 249 250 def test_exit_not_standalone():251 @click.command()252 @click.pass_context253 def cli(ctx):254 ctx.exit(1)255 251- assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 1256+ assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1257 258 @click.command()259 @click.pass_context260 def cli(ctx):261 ctx.exit(0)262 258- assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0263+ assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0modified:tests/test_defaults.py+12 added-12 removed
1 unmodified line2 3 4 def test_basic_defaults(runner):5 @click.command()6- @click.option('--foo', default=42, type=click.FLOAT)6+ @click.option("--foo", default=42, type=click.FLOAT)7 def cli(foo):8 assert type(foo) is float9- click.echo('FOO:[%s]' % foo)9+ click.echo("FOO:[%s]" % foo)10 11 result = runner.invoke(cli, [])12 assert not result.exception13- assert 'FOO:[42.0]' in result.output13+ assert "FOO:[42.0]" in result.output14 15 16 def test_multiple_defaults(runner):17 @click.command()18- @click.option('--foo', default=[23, 42], type=click.FLOAT,19- multiple=True)18+ @click.option("--foo", default=[23, 42], type=click.FLOAT, multiple=True)19 def cli(foo):20 for item in foo:21 assert type(item) is float22 click.echo(item)23 24 result = runner.invoke(cli, [])25 assert not result.exception26 assert result.output.splitlines() == [28- '23.0',29- '42.0',27+ "23.0",28+ "42.0",29 ]30 31 32 def test_nargs_plus_multiple(runner):33 @click.command()35- @click.option('--arg', default=((1, 2), (3, 4)),36- nargs=2, multiple=True, type=click.INT)34+ @click.option(35+ "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT36+ )37 def cli(arg):38 for item in arg:39- click.echo('<%d|%d>' % item)39+ click.echo("<%d|%d>" % item)40 41 result = runner.invoke(cli, [])42 assert not result.exception43 assert result.output.splitlines() == [44- '<1|2>',45- '<3|4>',44+ "<1|2>",45+ "<3|4>",46 ]modified:tests/test_formatting.py+133 added-131 removed
23 unmodified lines24 And this is a paragraph25 that will be rewrapped again.26 """27 28- result = runner.invoke(cli, ['--help'], terminal_width=60)28+ result = runner.invoke(cli, ["--help"], terminal_width=60)29 assert not result.exception30 assert result.output.splitlines() == [31- 'Usage: cli [OPTIONS]',32- '',33- ' First paragraph.',34- '',35- ' This is a very long second paragraph and not correctly',36- ' wrapped but it will be rewrapped.',37- '',38- ' This is',39- ' a paragraph',40- ' without rewrapping.',41- '',42- ' 1',43- ' 2',44- ' 3',45- '',46- ' And this is a paragraph that will be rewrapped again.',47- '',48- 'Options:',49- ' --help Show this message and exit.',31+ "Usage: cli [OPTIONS]",32+ "",33+ " First paragraph.",34+ "",35+ " This is a very long second paragraph and not correctly",36+ " wrapped but it will be rewrapped.",37+ "",38+ " This is",39+ " a paragraph",40+ " without rewrapping.",41+ "",42+ " 1",43+ " 2",44+ " 3",45+ "",46+ " And this is a paragraph that will be rewrapped again.",47+ "",48+ "Options:",49+ " --help Show this message and exit.",50 ]51 52 53 def test_wrapping_long_options_strings(runner):7 unmodified lines61 """Second level62 """63 64 @a_very_long.command()65- @click.argument('first')66- @click.argument('second')67- @click.argument('third')68- @click.argument('fourth')69- @click.argument('fifth')70- @click.argument('sixth')65+ @click.argument("first")66+ @click.argument("second")67+ @click.argument("third")68+ @click.argument("fourth")69+ @click.argument("fifth")70+ @click.argument("sixth")71 def command():72 """A command.73 """74 75 # 54 is chosen as a length where the second line is one character76 # longer than the maximum length.77- result = runner.invoke(cli, ['a-very-long', 'command', '--help'],78- terminal_width=54)77+ result = runner.invoke(cli, ["a-very-long", "command", "--help"], terminal_width=54)78 assert not result.exception79 assert result.output.splitlines() == [81- 'Usage: cli a-very-long command [OPTIONS] FIRST SECOND',82- ' THIRD FOURTH FIFTH',83- ' SIXTH',84- '',85- ' A command.',86- '',87- 'Options:',88- ' --help Show this message and exit.',80+ "Usage: cli a-very-long command [OPTIONS] FIRST SECOND",81+ " THIRD FOURTH FIFTH",82+ " SIXTH",83+ "",84+ " A command.",85+ "",86+ "Options:",87+ " --help Show this message and exit.",88 ]89 90 91 def test_wrapping_long_command_name(runner):7 unmodified lines99 """Second level100 """101 102 @a_very_very_very_long.command()104- @click.argument('first')105- @click.argument('second')106- @click.argument('third')107- @click.argument('fourth')108- @click.argument('fifth')109- @click.argument('sixth')103+ @click.argument("first")104+ @click.argument("second")105+ @click.argument("third")106+ @click.argument("fourth")107+ @click.argument("fifth")108+ @click.argument("sixth")109 def command():110 """A command.111 """112 114- result = runner.invoke(cli, ['a-very-very-very-long', 'command', '--help'],115- terminal_width=54)113+ result = runner.invoke(114+ cli, ["a-very-very-very-long", "command", "--help"], terminal_width=54115+ )116 assert not result.exception117 assert result.output.splitlines() == [118- 'Usage: cli a-very-very-very-long command ',119- ' [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH',120- ' SIXTH',121- '',122- ' A command.',123- '',124- 'Options:',125- ' --help Show this message and exit.',118+ "Usage: cli a-very-very-very-long command ",119+ " [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH",120+ " SIXTH",121+ "",122+ " A command.",123+ "",124+ "Options:",125+ " --help Show this message and exit.",126 ]127 128 129 def test_formatting_empty_help_lines(runner):2 unmodified lines132 """Top level command133 134 """135 136- result = runner.invoke(cli, ['--help'])136+ result = runner.invoke(cli, ["--help"])137 assert not result.exception138 assert result.output.splitlines() == [139- 'Usage: cli [OPTIONS]',140- '',141- ' Top level command',142- '',143- '',144- '',145- 'Options:',146- ' --help Show this message and exit.',139+ "Usage: cli [OPTIONS]",140+ "",141+ " Top level command",142+ "",143+ "",144+ "",145+ "Options:",146+ " --help Show this message and exit.",147 ]148 149 150 def test_formatting_usage_error(runner):151 @click.command()152- @click.argument('arg')152+ @click.argument("arg")153 def cmd(arg):154- click.echo('arg:' + arg)154+ click.echo("arg:" + arg)155 156 result = runner.invoke(cmd, [])157 assert result.exit_code == 2158 assert result.output.splitlines() == [159- 'Usage: cmd [OPTIONS] ARG',159+ "Usage: cmd [OPTIONS] ARG",160 'Try "cmd --help" for help.',161- '',162- 'Error: Missing argument "ARG".'161+ "",162+ 'Error: Missing argument "ARG".',163 ]164 165 166 def test_formatting_usage_error_metavar_missing_arg(runner):167 """168 :author: @r-m-n169 Including attribution to #612170 """171+172 @click.command()172- @click.argument('arg', metavar='metavar')173+ @click.argument("arg", metavar="metavar")174 def cmd(arg):175 pass176 177 result = runner.invoke(cmd, [])178 assert result.exit_code == 2179 assert result.output.splitlines() == [179- 'Usage: cmd [OPTIONS] metavar',180+ "Usage: cmd [OPTIONS] metavar",181 'Try "cmd --help" for help.',181- '',182- 'Error: Missing argument "metavar".'182+ "",183+ 'Error: Missing argument "metavar".',184 ]185 186 187 def test_formatting_usage_error_metavar_bad_arg(runner):188 @click.command()188- @click.argument('arg', type=click.INT, metavar='metavar')189+ @click.argument("arg", type=click.INT, metavar="metavar")190 def cmd(arg):191 pass192 192- result = runner.invoke(cmd, ['3.14'])193+ result = runner.invoke(cmd, ["3.14"])194 assert result.exit_code == 2195 assert result.output.splitlines() == [195- 'Usage: cmd [OPTIONS] metavar',196+ "Usage: cmd [OPTIONS] metavar",197 'Try "cmd --help" for help.',197- '',198- 'Error: Invalid value for "metavar": 3.14 is not a valid integer'198+ "",199+ 'Error: Invalid value for "metavar": 3.14 is not a valid integer',200 ]201 202 203 def test_formatting_usage_error_nested(runner):1 unmodified line205 def cmd():206 pass207 208 @cmd.command()208- @click.argument('bar')209+ @click.argument("bar")210 def foo(bar):210- click.echo('foo:' + bar)211+ click.echo("foo:" + bar)212 212- result = runner.invoke(cmd, ['foo'])213+ result = runner.invoke(cmd, ["foo"])214 assert result.exit_code == 2215 assert result.output.splitlines() == [215- 'Usage: cmd foo [OPTIONS] BAR',216+ "Usage: cmd foo [OPTIONS] BAR",217 'Try "cmd foo --help" for help.',217- '',218- 'Error: Missing argument "BAR".'218+ "",219+ 'Error: Missing argument "BAR".',220 ]221 222 223 def test_formatting_usage_error_no_help(runner):224 @click.command(add_help_option=False)224- @click.argument('arg')225+ @click.argument("arg")226 def cmd(arg):226- click.echo('arg:' + arg)227+ click.echo("arg:" + arg)228 229 result = runner.invoke(cmd, [])230 assert result.exit_code == 2231 assert result.output.splitlines() == [231- 'Usage: cmd [OPTIONS] ARG',232- '',233- 'Error: Missing argument "ARG".'232+ "Usage: cmd [OPTIONS] ARG",233+ "",234+ 'Error: Missing argument "ARG".',235 ]236 237 238 def test_formatting_usage_custom_help(runner):238- @click.command(context_settings=dict(help_option_names=['--man']))239- @click.argument('arg')239+ @click.command(context_settings=dict(help_option_names=["--man"]))240+ @click.argument("arg")241 def cmd(arg):241- click.echo('arg:' + arg)242+ click.echo("arg:" + arg)243 244 result = runner.invoke(cmd, [])245 assert result.exit_code == 2246 assert result.output.splitlines() == [246- 'Usage: cmd [OPTIONS] ARG',247+ "Usage: cmd [OPTIONS] ARG",248 'Try "cmd --man" for help.',248- '',249- 'Error: Missing argument "ARG".'249+ "",250+ 'Error: Missing argument "ARG".',251 ]252 253+254 def test_formatting_custom_type_metavar(runner):255 class MyType(click.ParamType):256 def get_metavar(self, param):257 return "MY_TYPE"3 unmodified lines261 @click.argument("param", type=MyType())262 def cmd(param):263 pass264 263- result = runner.invoke(cmd, '--help')265+ result = runner.invoke(cmd, "--help")266 assert not result.exception267 assert result.output.splitlines() == [266- 'Usage: foo [OPTIONS] MY_TYPE',267- '',268- 'Options:',269- ' --help Show this message and exit.'268+ "Usage: foo [OPTIONS] MY_TYPE",269+ "",270+ "Options:",271+ " --help Show this message and exit.",272 ]273 274 275 def test_truncating_docstring(runner):9 unmodified lines285 286 :param click.core.Context ctx: Click context.287 """288 287- result = runner.invoke(cli, ['--help'], terminal_width=60)289+ result = runner.invoke(cli, ["--help"], terminal_width=60)290 assert not result.exception291 assert result.output.splitlines() == [290- 'Usage: cli [OPTIONS]',291- '',292- ' First paragraph.',293- '',294- ' This is a very long second paragraph and not correctly',295- ' wrapped but it will be rewrapped.',296- '',297- 'Options:',298- ' --help Show this message and exit.',292+ "Usage: cli [OPTIONS]",293+ "",294+ " First paragraph.",295+ "",296+ " This is a very long second paragraph and not correctly",297+ " wrapped but it will be rewrapped.",298+ "",299+ "Options:",300+ " --help Show this message and exit.",301 ]302 303 304 def test_global_show_default(runner):1 unmodified line306 @click.option("-f", "in_file", default="out.txt", help="Output file name")307 def cli():308 pass309 308- result = runner.invoke(cli, ['--help'],)310+ result = runner.invoke(cli, ["--help"],)311 assert result.output.splitlines() == [310- 'Usage: cli [OPTIONS]',311- '',312- 'Options:',313- ' -f TEXT Output file name [default: out.txt]',314- ' --help Show this message and exit. [default: False]'312+ "Usage: cli [OPTIONS]",313+ "",314+ "Options:",315+ " -f TEXT Output file name [default: out.txt]",316+ " --help Show this message and exit. [default: False]",317 ]318 319 320 def test_formatting_usage_multiline_option_padding(runner):319- @click.command('foo')320- @click.option('--bar', help='This help message will be padded if it wraps.')321+ @click.command("foo")322+ @click.option("--bar", help="This help message will be padded if it wraps.")323 def cli():324 pass325 324- result = runner.invoke(cli, '--help', terminal_width=45)326+ result = runner.invoke(cli, "--help", terminal_width=45)327 assert not result.exception328 assert result.output.splitlines() == [327- 'Usage: foo [OPTIONS]',328- '',329- 'Options:',330- ' --bar TEXT This help message will be',331- ' padded if it wraps.',332- '',333- ' --help Show this message and exit.'329+ "Usage: foo [OPTIONS]",330+ "",331+ "Options:",332+ " --bar TEXT This help message will be",333+ " padded if it wraps.",334+ "",335+ " --help Show this message and exit.",336 ]337 338 339 def test_formatting_usage_no_option_padding(runner):338- @click.command('foo')339- @click.option('--bar', help='This help message will be padded if it wraps.')340+ @click.command("foo")341+ @click.option("--bar", help="This help message will be padded if it wraps.")342 def cli():343 pass344 343- result = runner.invoke(cli, '--help', terminal_width=80)345+ result = runner.invoke(cli, "--help", terminal_width=80)346 assert not result.exception347 assert result.output.splitlines() == [346- 'Usage: foo [OPTIONS]',347- '',348- 'Options:',349- ' --bar TEXT This help message will be padded if it wraps.',350- ' --help Show this message and exit.'348+ "Usage: foo [OPTIONS]",349+ "",350+ "Options:",351+ " --bar TEXT This help message will be padded if it wraps.",352+ " --help Show this message and exit.",353 ]modified:tests/test_imports.py+32 added-13 removed
3 unmodified lines4 5 from click._compat import WIN6 7 8-IMPORT_TEST = b'''\8+IMPORT_TEST = b"""\9 try:10 import __builtin__ as builtins11 except ImportError:12 import builtins13 unmodified lines26 import click27 rv = list(found_imports)28 import json29 click.echo(json.dumps(rv))30-'''30+"""31 32-ALLOWED_IMPORTS = set([33- 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',34- 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',35- 'threading', 'colorama', 'errno', 'fcntl', 'datetime', 'pipes', 'shlex'36-])32+ALLOWED_IMPORTS = set(33+ [34+ "weakref",35+ "os",36+ "struct",37+ "collections",38+ "sys",39+ "contextlib",40+ "functools",41+ "stat",42+ "re",43+ "codecs",44+ "inspect",45+ "itertools",46+ "io",47+ "threading",48+ "colorama",49+ "errno",50+ "fcntl",51+ "datetime",52+ "pipes",53+ "shlex",54+ ]55+)56 57 if WIN:39- ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',40- 'zlib'])58+ ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])59 60 61 def test_light_imports():44- c = subprocess.Popen([sys.executable, '-'], stdin=subprocess.PIPE,45- stdout=subprocess.PIPE)62+ c = subprocess.Popen(63+ [sys.executable, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE64+ )65 rv = c.communicate(IMPORT_TEST)[0]66 67 if sys.version_info[0] != 2:49- rv = rv.decode('utf-8')68+ rv = rv.decode("utf-8")69 imported = json.loads(rv)70 71 for module in imported:53- if module == 'click' or module.startswith('click.'):72+ if module == "click" or module.startswith("click."):73 continue74 assert module in ALLOWED_IMPORTSmodified:tests/test_normalization.py+10 added-10 removed
4 unmodified lines5 6 7 def test_option_normalization(runner):8 @click.command(context_settings=CONTEXT_SETTINGS)9- @click.option('--foo')10- @click.option('-x')9+ @click.option("--foo")10+ @click.option("-x")11 def cli(foo, x):12 click.echo(foo)13 click.echo(x)14 15- result = runner.invoke(cli, ['--FOO', '42', '-X', 23])16- assert result.output == '42\n23\n'15+ result = runner.invoke(cli, ["--FOO", "42", "-X", 23])16+ assert result.output == "42\n23\n"17 18 19 def test_choice_normalization(runner):20 @click.command(context_settings=CONTEXT_SETTINGS)21- @click.option('--choice', type=click.Choice(['Foo', 'Bar']))21+ @click.option("--choice", type=click.Choice(["Foo", "Bar"]))22 def cli(choice):23 click.echo(choice)24 25- result = runner.invoke(cli, ['--CHOICE', 'FOO'])26- assert result.output == 'Foo\n'25+ result = runner.invoke(cli, ["--CHOICE", "FOO"])26+ assert result.output == "Foo\n"27 28 29 def test_command_normalization(runner):30 @click.group(context_settings=CONTEXT_SETTINGS)1 unmodified line32 pass33 34 @cli.command()35 def foo():36- click.echo('here!')36+ click.echo("here!")37 38- result = runner.invoke(cli, ['FOO'])39- assert result.output == 'here!\n'38+ result = runner.invoke(cli, ["FOO"])39+ assert result.output == "here!\n"modified:tests/test_options.py+212 added-198 removed
8 unmodified lines9 10 11 def test_prefixes(runner):12 @click.command()13- @click.option('++foo', is_flag=True, help='das foo')14- @click.option('--bar', is_flag=True, help='das bar')13+ @click.option("++foo", is_flag=True, help="das foo")14+ @click.option("--bar", is_flag=True, help="das bar")15 def cli(foo, bar):16- click.echo('foo=%s bar=%s' % (foo, bar))16+ click.echo("foo=%s bar=%s" % (foo, bar))17 18- result = runner.invoke(cli, ['++foo', '--bar'])18+ result = runner.invoke(cli, ["++foo", "--bar"])19 assert not result.exception20- assert result.output == 'foo=True bar=True\n'20+ assert result.output == "foo=True bar=True\n"21 22- result = runner.invoke(cli, ['--help'])23- assert re.search(r'\+\+foo\s+das foo', result.output) is not None24- assert re.search(r'--bar\s+das bar', result.output) is not None22+ result = runner.invoke(cli, ["--help"])23+ assert re.search(r"\+\+foo\s+das foo", result.output) is not None24+ assert re.search(r"--bar\s+das bar", result.output) is not None25 26 27 def test_invalid_option(runner):28 try:29+30 @click.command()30- @click.option('foo')31+ @click.option("foo")32 def cli(foo):33 pass34+35 except TypeError as e:34- assert 'No options defined but a name was passed (foo).' \35- in str(e)36+ assert "No options defined but a name was passed (foo)." in str(e)37 else:37- assert False, 'Expected a type error because of an invalid option.'38+ assert False, "Expected a type error because of an invalid option."39 40 41 def test_invalid_nargs(runner):42 try:43+44 @click.command()43- @click.option('--foo', nargs=-1)45+ @click.option("--foo", nargs=-1)46 def cli(foo):47 pass48+49 except TypeError as e:47- assert 'Options cannot have nargs < 0' in str(e)50+ assert "Options cannot have nargs < 0" in str(e)51 else:49- assert False, 'Expected a type error because of an invalid option.'52+ assert False, "Expected a type error because of an invalid option."53 54 55 def test_nargs_tup_composite_mult(runner):56 @click.command()54- @click.option('--item', type=(str, int), multiple=True)57+ @click.option("--item", type=(str, int), multiple=True)58 def copy(item):59 for item in item:57- click.echo('name=%s id=%d' % item)60+ click.echo("name=%s id=%d" % item)61 59- result = runner.invoke(copy, ['--item', 'peter', '1', '--item', 'max', '2'])62+ result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])63 assert not result.exception64 assert result.output.splitlines() == [62- 'name=peter id=1',63- 'name=max id=2',65+ "name=peter id=1",66+ "name=max id=2",67 ]68 69 70 def test_counting(runner):71 @click.command()69- @click.option('-v', count=True, help='Verbosity',70- type=click.IntRange(0, 3))72+ @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))73 def cli(v):72- click.echo('verbosity=%d' % v)74+ click.echo("verbosity=%d" % v)75 74- result = runner.invoke(cli, ['-vvv'])76+ result = runner.invoke(cli, ["-vvv"])77 assert not result.exception76- assert result.output == 'verbosity=3\n'78+ assert result.output == "verbosity=3\n"79 78- result = runner.invoke(cli, ['-vvvv'])80+ result = runner.invoke(cli, ["-vvvv"])81 assert result.exception80- assert 'Invalid value for "-v": 4 is not in the valid range of 0 to 3.' \82+ assert (83+ 'Invalid value for "-v": 4 is not in the valid range of 0 to 3.'84 in result.output85+ )86 87 result = runner.invoke(cli, [])88 assert not result.exception85- assert result.output == 'verbosity=0\n'89+ assert result.output == "verbosity=0\n"90 87- result = runner.invoke(cli, ['--help'])88- assert re.search(r'-v\s+Verbosity', result.output) is not None91+ result = runner.invoke(cli, ["--help"])92+ assert re.search(r"-v\s+Verbosity", result.output) is not None93 94 91-@pytest.mark.parametrize('unknown_flag', ['--foo', '-f'])95+@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])96 def test_unknown_options(runner, unknown_flag):97 @click.command()98 def cli():99 pass100 101 result = runner.invoke(cli, [unknown_flag])102 assert result.exception99- assert 'no such option: {0}'.format(unknown_flag) in result.output103+ assert "no such option: {0}".format(unknown_flag) in result.output104 105 106 def test_multiple_required(runner):107 @click.command()104- @click.option('-m', '--message', multiple=True, required=True)108+ @click.option("-m", "--message", multiple=True, required=True)109 def cli(message):106- click.echo('\n'.join(message))110+ click.echo("\n".join(message))111 108- result = runner.invoke(cli, ['-m', 'foo', '-mbar'])112+ result = runner.invoke(cli, ["-m", "foo", "-mbar"])113 assert not result.exception110- assert result.output == 'foo\nbar\n'114+ assert result.output == "foo\nbar\n"115 116 result = runner.invoke(cli, [])117 assert result.exception118 assert 'Error: Missing option "-m" / "--message".' in result.output119 120 121 def test_empty_envvar(runner):122 @click.command()119- @click.option('--mypath', type=click.Path(exists=True), envvar='MYPATH')123+ @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")124 def cli(mypath):121- click.echo('mypath: %s' % mypath)125+ click.echo("mypath: %s" % mypath)126 123- result = runner.invoke(cli, [], env={'MYPATH': ''})127+ result = runner.invoke(cli, [], env={"MYPATH": ""})128 assert result.exit_code == 0125- assert result.output == 'mypath: None\n'129+ assert result.output == "mypath: None\n"130 131 132 def test_multiple_envvar(runner):133 @click.command()130- @click.option('--arg', multiple=True)134+ @click.option("--arg", multiple=True)135 def cmd(arg):132- click.echo('|'.join(arg))136+ click.echo("|".join(arg))137 134- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',135- env={'TEST_ARG': 'foo bar baz'})138+ result = runner.invoke(139+ cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}140+ )141 assert not result.exception137- assert result.output == 'foo|bar|baz\n'142+ assert result.output == "foo|bar|baz\n"143 144 @click.command()140- @click.option('--arg', multiple=True, envvar='X')145+ @click.option("--arg", multiple=True, envvar="X")146 def cmd(arg):142- click.echo('|'.join(arg))147+ click.echo("|".join(arg))148 144- result = runner.invoke(cmd, [], env={'X': 'foo bar baz'})149+ result = runner.invoke(cmd, [], env={"X": "foo bar baz"})150 assert not result.exception146- assert result.output == 'foo|bar|baz\n'151+ assert result.output == "foo|bar|baz\n"152 153 @click.command()149- @click.option('--arg', multiple=True, type=click.Path())154+ @click.option("--arg", multiple=True, type=click.Path())155 def cmd(arg):151- click.echo('|'.join(arg))156+ click.echo("|".join(arg))157 153- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',154- env={'TEST_ARG': 'foo%sbar' % os.path.pathsep})158+ result = runner.invoke(159+ cmd,160+ [],161+ auto_envvar_prefix="TEST",162+ env={"TEST_ARG": "foo%sbar" % os.path.pathsep},163+ )164 assert not result.exception156- assert result.output == 'foo|bar\n'165+ assert result.output == "foo|bar\n"166 167 168 def test_multiple_default_help(runner):169 @click.command()161- @click.option('--arg1', multiple=True, default=('foo', 'bar'),162- show_default=True)163- @click.option('--arg2', multiple=True, default=(1, 2), type=int,164- show_default=True)170+ @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)171+ @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)172 def cmd(arg, arg2):173 pass174 168- result = runner.invoke(cmd, ['--help'])175+ result = runner.invoke(cmd, ["--help"])176 assert not result.exception170- assert 'foo, bar' in result.output171- assert '1, 2' in result.output177+ assert "foo, bar" in result.output178+ assert "1, 2" in result.output179 180 181 def test_multiple_default_type(runner):182 @click.command()176- @click.option('--arg1', multiple=True, default=('foo', 'bar'))177- @click.option('--arg2', multiple=True, default=(1, 'a'))183+ @click.option("--arg1", multiple=True, default=("foo", "bar"))184+ @click.option("--arg2", multiple=True, default=(1, "a"))185 def cmd(arg1, arg2):186 assert all(isinstance(e[0], text_type) for e in arg1)187 assert all(isinstance(e[1], text_type) for e in arg1)188 189 assert all(isinstance(e[0], int) for e in arg2)190 assert all(isinstance(e[1], text_type) for e in arg2)191 185- result = runner.invoke(cmd, '--arg1 a b --arg1 test 1 --arg2 2 '186- 'two --arg2 4 four'.split())192+ result = runner.invoke(193+ cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()194+ )195 assert not result.exception196 197+198 def test_dynamic_default_help_unset(runner):199 @click.command()200+ @click.option(201+ "--username",191- @click.option('--username', prompt=True,192- default=lambda: os.environ.get('USER', ''),193- show_default=True)202+ prompt=True,203+ default=lambda: os.environ.get("USER", ""),204+ show_default=True,205+ )206 def cmd(username):207 print("Hello,", username)208 197- result = runner.invoke(cmd, ['--help'])209+ result = runner.invoke(cmd, ["--help"])210 assert result.exit_code == 0199- assert '--username' in result.output200- assert 'lambda' not in result.output201- assert '(dynamic)' in result.output211+ assert "--username" in result.output212+ assert "lambda" not in result.output213+ assert "(dynamic)" in result.output214 215+216 def test_dynamic_default_help_text(runner):217 @click.command()205- @click.option('--username', prompt=True,206- default=lambda: os.environ.get('USER', ''),207- show_default='current user')218+ @click.option(219+ "--username",220+ prompt=True,221+ default=lambda: os.environ.get("USER", ""),222+ show_default="current user",223+ )224 def cmd(username):225 print("Hello,", username)226 211- result = runner.invoke(cmd, ['--help'])227+ result = runner.invoke(cmd, ["--help"])228 assert result.exit_code == 0213- assert '--username' in result.output214- assert 'lambda' not in result.output215- assert '(current user)' in result.output229+ assert "--username" in result.output230+ assert "lambda" not in result.output231+ assert "(current user)" in result.output232 233 234 def test_toupper_envvar_prefix(runner):235 @click.command()220- @click.option('--arg')236+ @click.option("--arg")237 def cmd(arg):238 click.echo(arg)239 224- result = runner.invoke(cmd, [], auto_envvar_prefix='test',225- env={'TEST_ARG': 'foo'})240+ result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})241 assert not result.exception227- assert result.output == 'foo\n'242+ assert result.output == "foo\n"243 244 245 def test_nargs_envvar(runner):246 @click.command()232- @click.option('--arg', nargs=2)247+ @click.option("--arg", nargs=2)248 def cmd(arg):234- click.echo('|'.join(arg))249+ click.echo("|".join(arg))250 236- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',237- env={'TEST_ARG': 'foo bar'})251+ result = runner.invoke(252+ cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}253+ )254 assert not result.exception239- assert result.output == 'foo|bar\n'255+ assert result.output == "foo|bar\n"256 257 @click.command()242- @click.option('--arg', nargs=2, multiple=True)258+ @click.option("--arg", nargs=2, multiple=True)259 def cmd(arg):260 for item in arg:245- click.echo('|'.join(item))261+ click.echo("|".join(item))262 247- result = runner.invoke(cmd, [], auto_envvar_prefix='TEST',248- env={'TEST_ARG': 'x 1 y 2'})263+ result = runner.invoke(264+ cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}265+ )266 assert not result.exception250- assert result.output == 'x|1\ny|2\n'267+ assert result.output == "x|1\ny|2\n"268 269 270 def test_show_envvar(runner):271 @click.command()255- @click.option('--arg1', envvar='ARG1',256- show_envvar=True)272+ @click.option("--arg1", envvar="ARG1", show_envvar=True)273 def cmd(arg):274 pass275 260- result = runner.invoke(cmd, ['--help'])276+ result = runner.invoke(cmd, ["--help"])277 assert not result.exception262- assert 'ARG1' in result.output278+ assert "ARG1" in result.output279 280 281 def test_show_envvar_auto_prefix(runner):282 @click.command()267- @click.option('--arg1', show_envvar=True)283+ @click.option("--arg1", show_envvar=True)284 def cmd(arg):285 pass286 271- result = runner.invoke(cmd, ['--help'],272- auto_envvar_prefix='TEST')287+ result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")288 assert not result.exception274- assert 'TEST_ARG1' in result.output289+ assert "TEST_ARG1" in result.output290 291 292 def test_show_envvar_auto_prefix_dash_in_command(runner):293 @click.group()294 def cli():295 pass296 297 @cli.command()283- @click.option('--baz', show_envvar=True)298+ @click.option("--baz", show_envvar=True)299 def foo_bar(baz):300 pass301 287- result = runner.invoke(cli, ['foo-bar', '--help'],288- auto_envvar_prefix='TEST')302+ result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")303 assert not result.exception290- assert 'TEST_FOO_BAR_BAZ' in result.output304+ assert "TEST_FOO_BAR_BAZ" in result.output305 306 307 def test_custom_validation(runner):308 def validate_pos_int(ctx, param, value):309 if value < 0:296- raise click.BadParameter('Value needs to be positive')310+ raise click.BadParameter("Value needs to be positive")311 return value312 313 @click.command()300- @click.option('--foo', callback=validate_pos_int, default=1)314+ @click.option("--foo", callback=validate_pos_int, default=1)315 def cmd(foo):316 click.echo(foo)317 304- result = runner.invoke(cmd, ['--foo', '-1'])305- assert 'Invalid value for "--foo": Value needs to be positive' \306- in result.output318+ result = runner.invoke(cmd, ["--foo", "-1"])319+ assert 'Invalid value for "--foo": Value needs to be positive' in result.output320 308- result = runner.invoke(cmd, ['--foo', '42'])309- assert result.output == '42\n'321+ result = runner.invoke(cmd, ["--foo", "42"])322+ assert result.output == "42\n"323 324 325 def test_winstyle_options(runner):326 @click.command()314- @click.option('/debug;/no-debug', help='Enables or disables debug mode.')327+ @click.option("/debug;/no-debug", help="Enables or disables debug mode.")328 def cmd(debug):329 click.echo(debug)330 318- result = runner.invoke(cmd, ['/debug'], help_option_names=['/?'])319- assert result.output == 'True\n'320- result = runner.invoke(cmd, ['/no-debug'], help_option_names=['/?'])321- assert result.output == 'False\n'322- result = runner.invoke(cmd, [], help_option_names=['/?'])323- assert result.output == 'False\n'324- result = runner.invoke(cmd, ['/?'], help_option_names=['/?'])325- assert '/debug; /no-debug Enables or disables debug mode.' in result.output326- assert '/? Show this message and exit.' in result.output331+ result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])332+ assert result.output == "True\n"333+ result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])334+ assert result.output == "False\n"335+ result = runner.invoke(cmd, [], help_option_names=["/?"])336+ assert result.output == "False\n"337+ result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])338+ assert "/debug; /no-debug Enables or disables debug mode." in result.output339+ assert "/? Show this message and exit." in result.output340 341 342 def test_legacy_options(runner):343 @click.command()331- @click.option('-whatever')344+ @click.option("-whatever")345 def cmd(whatever):346 click.echo(whatever)347 335- result = runner.invoke(cmd, ['-whatever', '42'])336- assert result.output == '42\n'337- result = runner.invoke(cmd, ['-whatever=23'])338- assert result.output == '23\n'348+ result = runner.invoke(cmd, ["-whatever", "42"])349+ assert result.output == "42\n"350+ result = runner.invoke(cmd, ["-whatever=23"])351+ assert result.output == "23\n"352 353 354 def test_missing_option_string_cast():355 ctx = click.Context(click.Command(""))356 357 with pytest.raises(click.MissingParameter) as excinfo:345- click.Option(['-a'], required=True).full_process_value(ctx, None)358+ click.Option(["-a"], required=True).full_process_value(ctx, None)359 360 assert str(excinfo.value) == "missing parameter: a"361 362 363 def test_missing_choice(runner):364 @click.command()352- @click.option('--foo', type=click.Choice(['foo', 'bar']),353- required=True)365+ @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)366 def cmd(foo):367 click.echo(foo)368 369 result = runner.invoke(cmd)370 assert result.exit_code == 2359- error, separator, choices = result.output.partition('Choose from')371+ error, separator, choices = result.output.partition("Choose from")372 assert 'Error: Missing option "--foo". ' in error361- assert 'Choose from' in separator362- assert 'foo' in choices363- assert 'bar' in choices373+ assert "Choose from" in separator374+ assert "foo" in choices375+ assert "bar" in choices376 377 378 def test_case_insensitive_choice(runner):379 @click.command()368- @click.option('--foo', type=click.Choice(369- ['Orange', 'Apple'], case_sensitive=False))380+ @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))381 def cmd(foo):382 click.echo(foo)383 373- result = runner.invoke(cmd, ['--foo', 'apple'])384+ result = runner.invoke(cmd, ["--foo", "apple"])385 assert result.exit_code == 0375- assert result.output == 'Apple\n'386+ assert result.output == "Apple\n"387 377- result = runner.invoke(cmd, ['--foo', 'oRANGe'])388+ result = runner.invoke(cmd, ["--foo", "oRANGe"])389 assert result.exit_code == 0379- assert result.output == 'Orange\n'390+ assert result.output == "Orange\n"391 381- result = runner.invoke(cmd, ['--foo', 'Apple'])392+ result = runner.invoke(cmd, ["--foo", "Apple"])393 assert result.exit_code == 0383- assert result.output == 'Apple\n'394+ assert result.output == "Apple\n"395 396 @click.command()386- @click.option('--foo', type=click.Choice(['Orange', 'Apple']))397+ @click.option("--foo", type=click.Choice(["Orange", "Apple"]))398 def cmd2(foo):399 click.echo(foo)400 390- result = runner.invoke(cmd2, ['--foo', 'apple'])401+ result = runner.invoke(cmd2, ["--foo", "apple"])402 assert result.exit_code == 2403 393- result = runner.invoke(cmd2, ['--foo', 'oRANGe'])404+ result = runner.invoke(cmd2, ["--foo", "oRANGe"])405 assert result.exit_code == 2406 396- result = runner.invoke(cmd2, ['--foo', 'Apple'])407+ result = runner.invoke(cmd2, ["--foo", "Apple"])408 assert result.exit_code == 0409 410 411 def test_case_insensitive_choice_returned_exactly(runner):412 @click.command()402- @click.option('--foo', type=click.Choice(403- ['Orange', 'Apple'], case_sensitive=False))413+ @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))414 def cmd(foo):415 click.echo(foo)416 407- result = runner.invoke(cmd, ['--foo', 'apple'])417+ result = runner.invoke(cmd, ["--foo", "apple"])418 assert result.exit_code == 0409- assert result.output == 'Apple\n'419+ assert result.output == "Apple\n"420 421 422 def test_option_help_preserve_paragraphs(runner):423 @click.command()9 unmodified lines433 )434 def cmd(config):435 pass436 427- result = runner.invoke(cmd, ['--help'], )437+ result = runner.invoke(cmd, ["--help"],)438 assert result.exit_code == 0439 assert (440 " -C, --config PATH Configuration file to use.\n"441 "{i}\n"1 unmodified line443 "{i}consulted and used if set. If neither are given, a default\n"444 "{i}configuration file is loaded.".format(i=" " * 21)445 ) in result.output446 447+448 def test_argument_custom_class(runner):449 class CustomArgument(click.Argument):450 def get_default(self, ctx):440- '''a dumb override of a default value for testing'''441- return 'I am a default'451+ """a dumb override of a default value for testing"""452+ return "I am a default"453 454 @click.command()444- @click.argument('testarg', cls=CustomArgument, default='you wont see me')455+ @click.argument("testarg", cls=CustomArgument, default="you wont see me")456 def cmd(testarg):457 click.echo(testarg)458 459 result = runner.invoke(cmd)449- assert 'I am a default' in result.output450- assert 'you wont see me' not in result.output460+ assert "I am a default" in result.output461+ assert "you wont see me" not in result.output462 463 464 def test_option_custom_class(runner):465 class CustomOption(click.Option):466 def get_help_record(self, ctx):456- '''a dumb override of a help text for testing'''457- return ('--help', 'I am a help text')467+ """a dumb override of a help text for testing"""468+ return ("--help", "I am a help text")469 470 @click.command()460- @click.option('--testoption', cls=CustomOption, help='you wont see me')471+ @click.option("--testoption", cls=CustomOption, help="you wont see me")472 def cmd(testoption):473 click.echo(testoption)474 464- result = runner.invoke(cmd, ['--help'])465- assert 'I am a help text' in result.output466- assert 'you wont see me' not in result.output475+ result = runner.invoke(cmd, ["--help"])476+ assert "I am a help text" in result.output477+ assert "you wont see me" not in result.output478 479 480 def test_option_custom_class_reusable(runner):481 """Ensure we can reuse a custom class option. See Issue #926"""482 483 class CustomOption(click.Option):484 def get_help_record(self, ctx):474- '''a dumb override of a help text for testing'''475- return ('--help', 'I am a help text')485+ """a dumb override of a help text for testing"""486+ return ("--help", "I am a help text")487 488 # Assign to a variable to re-use the decorator.478- testoption = click.option('--testoption', cls=CustomOption, help='you wont see me')489+ testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")490 491 @click.command()492 @testoption493 def cmd1(testoption):6 unmodified lines500 501 # Both of the commands should have the --help option now.502 for cmd in (cmd1, cmd2):503 493- result = runner.invoke(cmd, ['--help'])494- assert 'I am a help text' in result.output495- assert 'you wont see me' not in result.output504+ result = runner.invoke(cmd, ["--help"])505+ assert "I am a help text" in result.output506+ assert "you wont see me" not in result.output507 508 509 def test_bool_flag_with_type(runner):510 @click.command()500- @click.option('--shout/--no-shout', default=False, type=bool)511+ @click.option("--shout/--no-shout", default=False, type=bool)512 def cmd(shout):513 pass514 515 result = runner.invoke(cmd)1 unmodified line517 518 519 def test_aliases_for_flags(runner):520 @click.command()510- @click.option('--warnings/--no-warnings', ' /-W', default=True)521+ @click.option("--warnings/--no-warnings", " /-W", default=True)522 def cli(warnings):523 click.echo(warnings)524 514- result = runner.invoke(cli, ['--warnings'])515- assert result.output == 'True\n'516- result = runner.invoke(cli, ['--no-warnings'])517- assert result.output == 'False\n'518- result = runner.invoke(cli, ['-W'])519- assert result.output == 'False\n'525+ result = runner.invoke(cli, ["--warnings"])526+ assert result.output == "True\n"527+ result = runner.invoke(cli, ["--no-warnings"])528+ assert result.output == "False\n"529+ result = runner.invoke(cli, ["-W"])530+ assert result.output == "False\n"531 532 @click.command()522- @click.option('--warnings/--no-warnings', '-w', default=True)533+ @click.option("--warnings/--no-warnings", "-w", default=True)534 def cli_alt(warnings):535 click.echo(warnings)536 526- result = runner.invoke(cli_alt, ['--warnings'])527- assert result.output == 'True\n'528- result = runner.invoke(cli_alt, ['--no-warnings'])529- assert result.output == 'False\n'530- result = runner.invoke(cli_alt, ['-w'])531- assert result.output == 'True\n'537+ result = runner.invoke(cli_alt, ["--warnings"])538+ assert result.output == "True\n"539+ result = runner.invoke(cli_alt, ["--no-warnings"])540+ assert result.output == "False\n"541+ result = runner.invoke(cli_alt, ["-w"])542+ assert result.output == "True\n"543 533-@pytest.mark.parametrize('option_args,expected', [534- (['--aggressive', '--all', '-a'], 'aggressive'),535- (['--first', '--second', '--third', '-a', '-b', '-c'], 'first'),536- (['--apple', '--banana', '--cantaloupe', '-a', '-b', '-c'], 'apple'),537- (['--cantaloupe', '--banana', '--apple', '-c', '-b', '-a'], 'cantaloupe'),538- (['-a', '-b', '-c'], 'a'),539- (['-c', '-b', '-a'], 'c'),540- (['-a', '--apple', '-b', '--banana', '-c', '--cantaloupe'], 'apple'),541- (['-c', '-a', '--cantaloupe', '-b', '--banana', '--apple'], 'cantaloupe'),542- (['--from', '-f', '_from'], '_from'),543- (['--return', '-r', '_ret'], '_ret'),544-])545-def test_option_names(runner, option_args, expected):544 545+@pytest.mark.parametrize(546+ "option_args,expected",547+ [548+ (["--aggressive", "--all", "-a"], "aggressive"),549+ (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),550+ (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),551+ (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),552+ (["-a", "-b", "-c"], "a"),553+ (["-c", "-b", "-a"], "c"),554+ (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),555+ (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),556+ (["--from", "-f", "_from"], "_from"),557+ (["--return", "-r", "_ret"], "_ret"),558+ ],559+)560+def test_option_names(runner, option_args, expected):561 @click.command()562 @click.option(*option_args, is_flag=True)563 def cmd(**kwargs):564 click.echo(str(kwargs[expected]))565 566 assert cmd.params[0].name == expected567 568 for form in option_args:555- if form.startswith('-'):569+ if form.startswith("-"):570 result = runner.invoke(cmd, [form])557- assert result.output == 'True\n'571+ assert result.output == "True\n"modified:tests/test_termui.py+115 added-94 removed
26 unmodified lines27 28 29 def test_progressbar_strip_regression(runner, monkeypatch):30 fake_clock = FakeClock()31- label = ' padded line'31+ label = " padded line"32 33 @click.command()34 def cli():35 with _create_progress(label=label) as progress:36 for thing in progress:37 fake_clock.advance_time()38 39- monkeypatch.setattr(time, 'time', fake_clock.time)40- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)39+ monkeypatch.setattr(time, "time", fake_clock.time)40+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)41 assert label in runner.invoke(cli, []).output42 43 44 def test_progressbar_length_hint(runner, monkeypatch):18 unmodified lines63 fake_clock = FakeClock()64 65 @click.command()66 def cli():67- with click.progressbar(Hinted(10), label='test') as progress:67+ with click.progressbar(Hinted(10), label="test") as progress:68 for thing in progress:69 fake_clock.advance_time()70 71- monkeypatch.setattr(time, 'time', fake_clock.time)72- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)71+ monkeypatch.setattr(time, "time", fake_clock.time)72+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)73 result = runner.invoke(cli, [])74 assert result.exception is None75 76 77 def test_progressbar_hidden(runner, monkeypatch):78 fake_clock = FakeClock()79- label = 'whatever'79+ label = "whatever"80 81 @click.command()82 def cli():83 with _create_progress(label=label) as progress:84 for thing in progress:85 fake_clock.advance_time()86 87- monkeypatch.setattr(time, 'time', fake_clock.time)88- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)89- assert runner.invoke(cli, []).output == ''87+ monkeypatch.setattr(time, "time", fake_clock.time)88+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)89+ assert runner.invoke(cli, []).output == ""90 91 92-@pytest.mark.parametrize('avg, expected', [([], 0.0), ([1, 4], 2.5)])92+@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])93 def test_progressbar_time_per_iteration(runner, avg, expected):94 with _create_progress(2, avg=avg) as progress:95 assert progress.time_per_iteration == expected96 97 98-@pytest.mark.parametrize('finished, expected', [(False, 5), (True, 0)])98+@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])99 def test_progressbar_eta(runner, finished, expected):100 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:101 assert progress.eta == expected102 103 104-@pytest.mark.parametrize('eta, expected',105- [(0, '00:00:00'), (30, '00:00:30'), (90, '00:01:30'), (900, '00:15:00'),106- (9000, '02:30:00'), (99999999999, '1157407d 09:46:39'), (None, '')])104+@pytest.mark.parametrize(105+ "eta, expected",106+ [107+ (0, "00:00:00"),108+ (30, "00:00:30"),109+ (90, "00:01:30"),110+ (900, "00:15:00"),111+ (9000, "02:30:00"),112+ (99999999999, "1157407d 09:46:39"),113+ (None, ""),114+ ],115+)116 def test_progressbar_format_eta(runner, eta, expected):117 with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:118 assert progress.format_eta() == expected119 120 112-@pytest.mark.parametrize('pos, length', [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])121+@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])122 def test_progressbar_format_pos(runner, pos, length):123 with _create_progress(length, length_known=length != 0, pos=pos) as progress:124 result = progress.format_pos()125 if progress.length_known:117- assert result == '%s/%s' % (pos, length)126+ assert result == "%s/%s" % (pos, length)127 else:128 assert result == str(pos)129 130 122-@pytest.mark.parametrize('length, finished, pos, avg, expected',123- [(8, False, 7, 0, '#######-'),124- (0, True, 8, 0, '########'),125- (0, False, 8, 0, '--------'),126- (0, False, 5, 3, '#-------')127- ])131+@pytest.mark.parametrize(132+ "length, finished, pos, avg, expected",133+ [134+ (8, False, 7, 0, "#######-"),135+ (0, True, 8, 0, "########"),136+ (0, False, 8, 0, "--------"),137+ (0, False, 5, 3, "#-------"),138+ ],139+)140 def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):129- with _create_progress(length,130- length_known=length != 0,131- width=8,132- pos=pos,133- finished=finished,134- avg=[avg]) as progress:141+ with _create_progress(142+ length, length_known=length != 0, width=8, pos=pos, finished=finished, avg=[avg]143+ ) as progress:144 assert progress.format_bar() == expected145 146 138-@pytest.mark.parametrize('length, length_known, show_percent, show_pos, pos, expected',139- [(0, True, True, True, 0, ' [--------] 0/0 0%'),140- (0, True, False, True, 0, ' [--------] 0/0'),141- (0, True, False, False, 0, ' [--------]'),142- (0, False, False, False, 0, ' [--------]'),143- (8, True, True, True, 8, ' [########] 8/8 100%')144- ])145-def test_progressbar_format_progress_line(runner, length, length_known, show_percent, show_pos, pos, expected):146- with _create_progress(length,147- length_known,148- width=8,149- show_percent=show_percent,150- pos=pos,151- show_pos=show_pos) as progress:147+@pytest.mark.parametrize(148+ "length, length_known, show_percent, show_pos, pos, expected",149+ [150+ (0, True, True, True, 0, " [--------] 0/0 0%"),151+ (0, True, False, True, 0, " [--------] 0/0"),152+ (0, True, False, False, 0, " [--------]"),153+ (0, False, False, False, 0, " [--------]"),154+ (8, True, True, True, 8, " [########] 8/8 100%"),155+ ],156+)157+def test_progressbar_format_progress_line(158+ runner, length, length_known, show_percent, show_pos, pos, expected159+):160+ with _create_progress(161+ length,162+ length_known,163+ width=8,164+ show_percent=show_percent,165+ pos=pos,166+ show_pos=show_pos,167+ ) as progress:168 assert progress.format_progress_line() == expected169 170 155-@pytest.mark.parametrize('test_item', ['test', None])171+@pytest.mark.parametrize("test_item", ["test", None])172 def test_progressbar_format_progress_line_with_show_func(runner, test_item):157-173 def item_show_func(item):174 return item175 161- with _create_progress(item_show_func=item_show_func, current_item=test_item) as progress:176+ with _create_progress(177+ item_show_func=item_show_func, current_item=test_item178+ ) as progress:179 if test_item:180 assert progress.format_progress_line().endswith(test_item)181 else:182 assert progress.format_progress_line().endswith(progress.format_pct())2 unmodified lines185 def test_progressbar_init_exceptions(runner):186 try:187 click.progressbar()188 except TypeError as e:172- assert str(e) == 'iterable or length is required'189+ assert str(e) == "iterable or length is required"190 else:174- assert False, 'Expected an exception because unspecified arguments'191+ assert False, "Expected an exception because unspecified arguments"192 193 194 def test_progressbar_iter_outside_with_exceptions(runner):195 try:196 progress = click.progressbar(length=2)197 iter(progress)198 except RuntimeError as e:182- assert str(e) == 'You need to use progress bars in a with block.'199+ assert str(e) == "You need to use progress bars in a with block."200 else:184- assert False, 'Expected an exception because of abort-related inputs.'201+ assert False, "Expected an exception because of abort-related inputs."202 203 204 def test_progressbar_is_iterator(runner, monkeypatch):205 fake_clock = FakeClock()206 207 @click.command()208 def cli():192- with click.progressbar(range(10), label='test') as progress:209+ with click.progressbar(range(10), label="test") as progress:210 while True:211 try:212 next(progress)213 fake_clock.advance_time()214 except StopIteration:215 break216 200- monkeypatch.setattr(time, 'time', fake_clock.time)201- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)217+ monkeypatch.setattr(time, "time", fake_clock.time)218+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)219 220 result = runner.invoke(cli, [])221 assert result.exception is None222 223 224 def test_choices_list_in_prompt(runner, monkeypatch):225 @click.command()209- @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),210- prompt=True)226+ @click.option(227+ "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True228+ )229 def cli_with_choices(g):230 pass231 232 @click.command()215- @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),216- prompt=True, show_choices=False)233+ @click.option(234+ "-g",235+ type=click.Choice(["none", "day", "week", "month"]),236+ prompt=True,237+ show_choices=False,238+ )239 def cli_without_choices(g):240 pass241 220- result = runner.invoke(cli_with_choices, [], input='none')221- assert '(none, day, week, month)' in result.output242+ result = runner.invoke(cli_with_choices, [], input="none")243+ assert "(none, day, week, month)" in result.output244 223- result = runner.invoke(cli_without_choices, [], input='none')224- assert '(none, day, week, month)' not in result.output245+ result = runner.invoke(cli_without_choices, [], input="none")246+ assert "(none, day, week, month)" not in result.output247 248 249 @pytest.mark.parametrize(228- "file_kwargs",229- [230- {"mode": "rt"},231- {"mode": "rb"},232- {"lazy": True},233- ]250+ "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True},]251 )252 def test_file_prompt_default_format(runner, file_kwargs):253 @click.command()254 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))7 unmodified lines262 def test_secho(runner):263 with runner.isolation() as outstreams:264 click.secho(None, nl=False)265 bytes = outstreams[0].getvalue()249- assert bytes == b''266+ assert bytes == b""267 268 269 def test_progressbar_yields_all_items(runner):270 with click.progressbar(range(3)) as progress:9 unmodified lines280 for _ in progress:281 fake_clock.advance_time()282 print("")283 267- monkeypatch.setattr(time, 'time', fake_clock.time)268- monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)284+ monkeypatch.setattr(time, "time", fake_clock.time)285+ monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)286 output = runner.invoke(cli, []).output287 271- lines = [line for line in output.split('\n') if '[' in line]288+ lines = [line for line in output.split("\n") if "[" in line]289 273- assert ' 25% 00:00:03' in lines[0]274- assert ' 50% 00:00:02' in lines[1]275- assert ' 75% 00:00:01' in lines[2]276- assert '100% ' in lines[3]290+ assert " 25% 00:00:03" in lines[0]291+ assert " 50% 00:00:02" in lines[1]292+ assert " 75% 00:00:01" in lines[2]293+ assert "100% " in lines[3]294 295 279-@pytest.mark.parametrize(280- 'key_char', (u'h', u'H', u'é', u'À', u' ', u'字', u'àH', u'àR')281-)282-@pytest.mark.parametrize('echo', [True, False])283-@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')296+@pytest.mark.parametrize("key_char", (u"h", u"H", u"é", u"À", u" ", u"字", u"àH", u"àR"))297+@pytest.mark.parametrize("echo", [True, False])298+@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")299 def test_getchar_windows(runner, monkeypatch, key_char, echo):285- monkeypatch.setattr(click._termui_impl.msvcrt, 'getwche', lambda: key_char)286- monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)287- monkeypatch.setattr(click.termui, '_getchar', None)300+ monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)301+ monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)302+ monkeypatch.setattr(click.termui, "_getchar", None)303 assert click.getchar(echo) == key_char304 305 291-@pytest.mark.parametrize('special_key_char, key_char', [(u'\x00', 'a'), (u'\x00', 'b'), (u'\xe0', 'c')])292-@pytest.mark.skipif(not WIN, reason='Tests special character inputs using the msvcrt module.')306+@pytest.mark.parametrize(307+ "special_key_char, key_char", [(u"\x00", "a"), (u"\x00", "b"), (u"\xe0", "c")]308+)309+@pytest.mark.skipif(310+ not WIN, reason="Tests special character inputs using the msvcrt module."311+)312 def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):313 ordered_inputs = [key_char, special_key_char]295- monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: ordered_inputs.pop())296- monkeypatch.setattr(click.termui, '_getchar', None)314+ monkeypatch.setattr(315+ click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()316+ )317+ monkeypatch.setattr(click.termui, "_getchar", None)318 assert click.getchar() == special_key_char + key_char319 320 300-@pytest.mark.parametrize('key_char', [u'\x03', u'\x1a'])301-@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')321+@pytest.mark.parametrize("key_char", [u"\x03", u"\x1a"])322+@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")323 def test_getchar_windows_exceptions(runner, monkeypatch, key_char):303- monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)304- monkeypatch.setattr(click.termui, '_getchar', None)324+ monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)325+ monkeypatch.setattr(click.termui, "_getchar", None)326 try:327 click.getchar()328 except KeyboardInterrupt:308- assert key_char == u'\x03'329+ assert key_char == u"\x03"330 except EOFError:310- assert key_char == u'\x1a'331+ assert key_char == u"\x1a"332 else:312- assert False, 'Expected an exception because of abort-specific inputs.'333+ assert False, "Expected an exception because of abort-specific inputs."modified:tests/test_testing.py+67 added-65 removed
16 unmodified lines17 18 def test_runner():19 @click.command()20 def test():21- i = click.get_binary_stream('stdin')22- o = click.get_binary_stream('stdout')21+ i = click.get_binary_stream("stdin")22+ o = click.get_binary_stream("stdout")23 while 1:24 chunk = i.read(4096)25 if not chunk:26 break27 o.write(chunk)28 o.flush()29 30 runner = CliRunner()31- result = runner.invoke(test, input='Hello World!\n')31+ result = runner.invoke(test, input="Hello World!\n")32 assert not result.exception33- assert result.output == 'Hello World!\n'33+ assert result.output == "Hello World!\n"34 35 runner = CliRunner(echo_stdin=True)36- result = runner.invoke(test, input='Hello World!\n')36+ result = runner.invoke(test, input="Hello World!\n")37 assert not result.exception38- assert result.output == 'Hello World!\nHello World!\n'38+ assert result.output == "Hello World!\nHello World!\n"39 40 41 def test_runner_with_stream():42 @click.command()43 def test():44- i = click.get_binary_stream('stdin')45- o = click.get_binary_stream('stdout')44+ i = click.get_binary_stream("stdin")45+ o = click.get_binary_stream("stdout")46 while 1:47 chunk = i.read(4096)48 if not chunk:49 break50 o.write(chunk)51 o.flush()52 53 runner = CliRunner()54- result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))54+ result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))55 assert not result.exception56- assert result.output == 'Hello World!\n'56+ assert result.output == "Hello World!\n"57 58 runner = CliRunner(echo_stdin=True)59- result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))59+ result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))60 assert not result.exception61- assert result.output == 'Hello World!\nHello World!\n'61+ assert result.output == "Hello World!\nHello World!\n"62 63 64 def test_prompts():65 @click.command()66- @click.option('--foo', prompt=True)66+ @click.option("--foo", prompt=True)67 def test(foo):68- click.echo('foo=%s' % foo)68+ click.echo("foo=%s" % foo)69 70 runner = CliRunner()71- result = runner.invoke(test, input='wau wau\n')71+ result = runner.invoke(test, input="wau wau\n")72 assert not result.exception73- assert result.output == 'Foo: wau wau\nfoo=wau wau\n'73+ assert result.output == "Foo: wau wau\nfoo=wau wau\n"74 75 @click.command()76- @click.option('--foo', prompt=True, hide_input=True)76+ @click.option("--foo", prompt=True, hide_input=True)77 def test(foo):78- click.echo('foo=%s' % foo)78+ click.echo("foo=%s" % foo)79 80 runner = CliRunner()81- result = runner.invoke(test, input='wau wau\n')81+ result = runner.invoke(test, input="wau wau\n")82 assert not result.exception83- assert result.output == 'Foo: \nfoo=wau wau\n'83+ assert result.output == "Foo: \nfoo=wau wau\n"84 85 86 def test_getchar():87 @click.command()88 def continue_it():89 click.echo(click.getchar())90 91 runner = CliRunner()92- result = runner.invoke(continue_it, input='y')92+ result = runner.invoke(continue_it, input="y")93 assert not result.exception94- assert result.output == 'y\n'94+ assert result.output == "y\n"95 96 97 def test_catch_exceptions():98 class CustomError(Exception):18 unmodified lines117 result = runner.invoke(cli)118 assert result.exit_code == 1119 120 121-@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')121+@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")122 def test_with_color():123 @click.command()124 def cli():125- click.secho('hello world', fg='blue')125+ click.secho("hello world", fg="blue")126 127 runner = CliRunner()128 129 result = runner.invoke(cli)130- assert result.output == 'hello world\n'130+ assert result.output == "hello world\n"131 assert not result.exception132 133 result = runner.invoke(cli, color=True)134- assert result.output == click.style('hello world', fg='blue') + '\n'134+ assert result.output == click.style("hello world", fg="blue") + "\n"135 assert not result.exception136 137 138 def test_with_color_but_pause_not_blocking():3 unmodified lines142 143 runner = CliRunner()144 result = runner.invoke(cli, color=True)145 assert not result.exception146- assert result.output == ''146+ assert result.output == ""147 148 149 def test_exit_code_and_output_from_sys_exit():150 # See issue #362151 @click.command()152 def cli_string():153- click.echo('hello world')154- sys.exit('error')153+ click.echo("hello world")154+ sys.exit("error")155 156 @click.command()157 @click.pass_context158 def cli_string_ctx_exit(ctx):159- click.echo('hello world')160- ctx.exit('error')159+ click.echo("hello world")160+ ctx.exit("error")161 162 @click.command()163 def cli_int():164- click.echo('hello world')164+ click.echo("hello world")165 sys.exit(1)166 167 @click.command()168 @click.pass_context169 def cli_int_ctx_exit(ctx):170- click.echo('hello world')170+ click.echo("hello world")171 ctx.exit(1)172 173 @click.command()174 def cli_float():175- click.echo('hello world')175+ click.echo("hello world")176 sys.exit(1.0)177 178 @click.command()179 @click.pass_context180 def cli_float_ctx_exit(ctx):181- click.echo('hello world')181+ click.echo("hello world")182 ctx.exit(1.0)183 184 @click.command()185 def cli_no_error():186- click.echo('hello world')186+ click.echo("hello world")187 188 runner = CliRunner()189 190 result = runner.invoke(cli_string)191 assert result.exit_code == 1192- assert result.output == 'hello world\nerror\n'192+ assert result.output == "hello world\nerror\n"193 194 result = runner.invoke(cli_string_ctx_exit)195 assert result.exit_code == 1196- assert result.output == 'hello world\nerror\n'196+ assert result.output == "hello world\nerror\n"197 198 result = runner.invoke(cli_int)199 assert result.exit_code == 1200- assert result.output == 'hello world\n'200+ assert result.output == "hello world\n"201 202 result = runner.invoke(cli_int_ctx_exit)203 assert result.exit_code == 1204- assert result.output == 'hello world\n'204+ assert result.output == "hello world\n"205 206 result = runner.invoke(cli_float)207 assert result.exit_code == 1208- assert result.output == 'hello world\n1.0\n'208+ assert result.output == "hello world\n1.0\n"209 210 result = runner.invoke(cli_float_ctx_exit)211 assert result.exit_code == 1212- assert result.output == 'hello world\n1.0\n'212+ assert result.output == "hello world\n1.0\n"213 214 result = runner.invoke(cli_no_error)215 assert result.exit_code == 0216- assert result.output == 'hello world\n'216+ assert result.output == "hello world\n"217 218 219 def test_env():220 @click.command()221 def cli_env():222- click.echo('ENV=%s' % os.environ['TEST_CLICK_ENV'])222+ click.echo("ENV=%s" % os.environ["TEST_CLICK_ENV"])223 224 runner = CliRunner()225 226 env_orig = dict(os.environ)227 env = dict(env_orig)228- assert 'TEST_CLICK_ENV' not in env229- env['TEST_CLICK_ENV'] = 'some_value'228+ assert "TEST_CLICK_ENV" not in env229+ env["TEST_CLICK_ENV"] = "some_value"230 result = runner.invoke(cli_env, env=env)231 assert result.exit_code == 0232- assert result.output == 'ENV=some_value\n'232+ assert result.output == "ENV=some_value\n"233 234 assert os.environ == env_orig235 236 6 unmodified lines243 runner = CliRunner(mix_stderr=False)244 245 result = runner.invoke(cli_stderr)246 247- assert result.output == 'stdout\n'248- assert result.stdout == 'stdout\n'249- assert result.stderr == 'stderr\n'247+ assert result.output == "stdout\n"248+ assert result.stdout == "stdout\n"249+ assert result.stderr == "stderr\n"250 251 runner_mix = CliRunner(mix_stderr=True)252 result_mix = runner_mix.invoke(cli_stderr)253 254- assert result_mix.output == 'stdout\nstderr\n'255- assert result_mix.stdout == 'stdout\nstderr\n'254+ assert result_mix.output == "stdout\nstderr\n"255+ assert result_mix.stdout == "stdout\nstderr\n"256 257 with pytest.raises(ValueError):258 result_mix.stderr259 4 unmodified lines264 runner = CliRunner(mix_stderr=False)265 266 result = runner.invoke(cli_empty_stderr)267 268- assert result.output == 'stdout\n'269- assert result.stdout == 'stdout\n'270- assert result.stderr == ''268+ assert result.output == "stdout\n"269+ assert result.stdout == "stdout\n"270+ assert result.stderr == ""271 272 273-@pytest.mark.parametrize('args, expected_output', [274- (None, 'bar\n'),275- ([], 'bar\n'),276- ('', 'bar\n'),277- (['--foo', 'one two'], 'one two\n'),278- ('--foo "one two"', 'one two\n'),279-])273+@pytest.mark.parametrize(274+ "args, expected_output",275+ [276+ (None, "bar\n"),277+ ([], "bar\n"),278+ ("", "bar\n"),279+ (["--foo", "one two"], "one two\n"),280+ ('--foo "one two"', "one two\n"),281+ ],282+)283 def test_args(args, expected_output):281-284 @click.command()283- @click.option('--foo', default='bar')285+ @click.option("--foo", default="bar")286 def cli_args(foo):287 click.echo(foo)288 289 runner = CliRunner()9 unmodified lines299 300 runner = CliRunner()301 result = runner.invoke(cli, prog_name="foobar")302 assert not result.exception301- assert result.output == 'ok\n'303+ assert result.output == "ok\n"modified:tests/test_utils.py+137 added-140 removed
10 unmodified lines11 12 13 def test_echo(runner):14 with runner.isolation() as outstreams:15- click.echo(u'\N{SNOWMAN}')16- click.echo(b'\x44\x44')15+ click.echo(u"\N{SNOWMAN}")16+ click.echo(b"\x44\x44")17 click.echo(42, nl=False)18- click.echo(b'a', nl=False)19- click.echo('\x1b[31mx\x1b[39m', nl=False)20- bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')21- assert bytes == b'\xe2\x98\x83\nDD\n42ax'18+ click.echo(b"a", nl=False)19+ click.echo("\x1b[31mx\x1b[39m", nl=False)20+ bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")21+ assert bytes == b"\xe2\x98\x83\nDD\n42ax"22 23 # If we are in Python 2, we expect that writing bytes into a string io24 # does not do anything crazy. In Python 325 if sys.version_info[0] == 2:26 import StringIO27+28 sys.stdout = x = StringIO.StringIO()29 try:29- click.echo('\xf6')30+ click.echo("\xf6")31 finally:32 sys.stdout = sys.__stdout__32- assert x.getvalue() == '\xf6\n'33+ assert x.getvalue() == "\xf6\n"34 35 # And in any case, if wrapped, we expect bytes to survive.36 @click.command()37 def cli():37- click.echo(b'\xf6')38+ click.echo(b"\xf6")39+40 result = runner.invoke(cli, [])39- assert result.stdout_bytes == b'\xf6\n'41+ assert result.stdout_bytes == b"\xf6\n"42 43 # Ensure we do not strip for bytes.44 with runner.isolation() as outstreams:43- click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)44- assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'45+ click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)46+ assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"47 48 49 def test_echo_custom_file():50 import io51+52 f = io.StringIO()50- click.echo(u'hello', file=f)51- assert f.getvalue() == u'hello\n'53+ click.echo(u"hello", file=f)54+ assert f.getvalue() == u"hello\n"55 56 57 @pytest.mark.parametrize(58 ("styles", "ref"),24 unmodified lines83 assert click.style("x y", **styles) == ref84 assert click.unstyle(ref) == "x y"85 86 84-@pytest.mark.parametrize(85- ("text", "expect"),86- [87- ("\x1b[?25lx y\x1b[?25h", "x y"),88- ]89-)87+@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y"),])88 def test_unstyle_other_ansi(text, expect):89 assert click.unstyle(text) == expect90 91 94-92 def test_filename_formatting():96- assert click.format_filename(b'foo.txt') == 'foo.txt'97- assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt'98- assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt'99- assert click.format_filename(u'/x/foo.txt', shorten=True) == 'foo.txt'93+ assert click.format_filename(b"foo.txt") == "foo.txt"94+ assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"95+ assert click.format_filename(u"/x/foo.txt") == "/x/foo.txt"96+ assert click.format_filename(u"/x/foo.txt", shorten=True) == "foo.txt"97 98 # filesystem encoding on windows permits this.99 if not WIN:103- assert click.format_filename(b'/x/foo\xff.txt', shorten=True) \104- == u'foo\ufffd.txt'100+ assert (101+ click.format_filename(b"/x/foo\xff.txt", shorten=True) == u"foo\ufffd.txt"102+ )103 104 105 def test_prompts(runner):106 @click.command()107 def test():110- if click.confirm('Foo'):111- click.echo('yes!')108+ if click.confirm("Foo"):109+ click.echo("yes!")110 else:113- click.echo('no :(')111+ click.echo("no :(")112 115- result = runner.invoke(test, input='y\n')113+ result = runner.invoke(test, input="y\n")114 assert not result.exception117- assert result.output == 'Foo [y/N]: y\nyes!\n'115+ assert result.output == "Foo [y/N]: y\nyes!\n"116 119- result = runner.invoke(test, input='\n')117+ result = runner.invoke(test, input="\n")118 assert not result.exception121- assert result.output == 'Foo [y/N]: \nno :(\n'119+ assert result.output == "Foo [y/N]: \nno :(\n"120 123- result = runner.invoke(test, input='n\n')121+ result = runner.invoke(test, input="n\n")122 assert not result.exception125- assert result.output == 'Foo [y/N]: n\nno :(\n'123+ assert result.output == "Foo [y/N]: n\nno :(\n"124 125 @click.command()126 def test_no():129- if click.confirm('Foo', default=True):130- click.echo('yes!')127+ if click.confirm("Foo", default=True):128+ click.echo("yes!")129 else:132- click.echo('no :(')130+ click.echo("no :(")131 134- result = runner.invoke(test_no, input='y\n')132+ result = runner.invoke(test_no, input="y\n")133 assert not result.exception136- assert result.output == 'Foo [Y/n]: y\nyes!\n'134+ assert result.output == "Foo [Y/n]: y\nyes!\n"135 138- result = runner.invoke(test_no, input='\n')136+ result = runner.invoke(test_no, input="\n")137 assert not result.exception140- assert result.output == 'Foo [Y/n]: \nyes!\n'138+ assert result.output == "Foo [Y/n]: \nyes!\n"139 142- result = runner.invoke(test_no, input='n\n')140+ result = runner.invoke(test_no, input="n\n")141 assert not result.exception144- assert result.output == 'Foo [Y/n]: n\nno :(\n'142+ assert result.output == "Foo [Y/n]: n\nno :(\n"143 144 147-@pytest.mark.skipif(WIN, reason='Different behavior on windows.')145+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")146 def test_prompts_abort(monkeypatch, capsys):147 def f(_):148 raise KeyboardInterrupt()149 152- monkeypatch.setattr('click.termui.hidden_prompt_func', f)150+ monkeypatch.setattr("click.termui.hidden_prompt_func", f)151 152 try:155- click.prompt('Password', hide_input=True)153+ click.prompt("Password", hide_input=True)154 except click.Abort:157- click.echo('Screw you.')155+ click.echo("Screw you.")156 157 out, err = capsys.readouterr()160- assert out == 'Password: \nScrew you.\n'158+ assert out == "Password: \nScrew you.\n"159 160 161 def _test_gen_func():164- yield 'a'165- yield 'b'166- yield 'c'167- yield 'abc'162+ yield "a"163+ yield "b"164+ yield "c"165+ yield "abc"166 167 170-@pytest.mark.skipif(WIN, reason='Different behavior on windows.')171-@pytest.mark.parametrize('cat', ['cat', 'cat ', 'cat '])172-@pytest.mark.parametrize('test', [173- # We need lambda here, because pytest will174- # reuse the parameters, and then the generators175- # are already used and will not yield anymore176- ('just text\n', lambda: 'just text'),177- ('iterable\n', lambda: ["itera", "ble"]),178- ('abcabc\n', lambda: _test_gen_func),179- ('abcabc\n', lambda: _test_gen_func()),180- ('012345\n', lambda: (c for c in range(6))),181-])168+@pytest.mark.skipif(WIN, reason="Different behavior on windows.")169+@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])170+@pytest.mark.parametrize(171+ "test",172+ [173+ # We need lambda here, because pytest will174+ # reuse the parameters, and then the generators175+ # are already used and will not yield anymore176+ ("just text\n", lambda: "just text"),177+ ("iterable\n", lambda: ["itera", "ble"]),178+ ("abcabc\n", lambda: _test_gen_func),179+ ("abcabc\n", lambda: _test_gen_func()),180+ ("012345\n", lambda: (c for c in range(6))),181+ ],182+)183 def test_echo_via_pager(monkeypatch, capfd, cat, test):183- monkeypatch.setitem(os.environ, 'PAGER', cat)184- monkeypatch.setattr(click._termui_impl, 'isatty', lambda x: True)184+ monkeypatch.setitem(os.environ, "PAGER", cat)185+ monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)186 187 expected_output = test[0]188 test_input = test[1]()189 2 unmodified lines192 out, err = capfd.readouterr()193 assert out == expected_output194 195 195-@pytest.mark.skipif(WIN, reason='Test does not make sense on Windows.')196+@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")197 def test_echo_color_flag(monkeypatch, capfd):198 isatty = True198- monkeypatch.setattr(click._compat, 'isatty', lambda x: isatty)199+ monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)200 200- text = 'foo'201- styled_text = click.style(text, fg='red')202- assert styled_text == '\x1b[31mfoo\x1b[0m'201+ text = "foo"202+ styled_text = click.style(text, fg="red")203+ assert styled_text == "\x1b[31mfoo\x1b[0m"204 205 click.echo(styled_text, color=False)206 out, err = capfd.readouterr()206- assert out == text + '\n'207+ assert out == text + "\n"208 209 click.echo(styled_text, color=True)210 out, err = capfd.readouterr()210- assert out == styled_text + '\n'211+ assert out == styled_text + "\n"212 213 isatty = True214 click.echo(styled_text)215 out, err = capfd.readouterr()215- assert out == styled_text + '\n'216+ assert out == styled_text + "\n"217 218 isatty = False219 click.echo(styled_text)220 out, err = capfd.readouterr()220- assert out == text + '\n'221+ assert out == text + "\n"222 223 223-@pytest.mark.skipif(WIN, reason='Test too complex to make work windows.')224+@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")225 def test_echo_writing_to_standard_error(capfd, monkeypatch):226 def emulate_input(text):227 """Emulate keyboard input."""228 if sys.version_info[0] == 2:229 from StringIO import StringIO230 else:231 from io import StringIO231- monkeypatch.setattr(sys, 'stdin', StringIO(text))232+ monkeypatch.setattr(sys, "stdin", StringIO(text))233 233- click.echo('Echo to standard output')234+ click.echo("Echo to standard output")235 out, err = capfd.readouterr()235- assert out == 'Echo to standard output\n'236- assert err == ''236+ assert out == "Echo to standard output\n"237+ assert err == ""238 238- click.echo('Echo to standard error', err=True)239+ click.echo("Echo to standard error", err=True)240 out, err = capfd.readouterr()240- assert out == ''241- assert err == 'Echo to standard error\n'241+ assert out == ""242+ assert err == "Echo to standard error\n"243 243- emulate_input('asdlkj\n')244- click.prompt('Prompt to stdin')244+ emulate_input("asdlkj\n")245+ click.prompt("Prompt to stdin")246 out, err = capfd.readouterr()246- assert out == 'Prompt to stdin: '247- assert err == ''247+ assert out == "Prompt to stdin: "248+ assert err == ""249 249- emulate_input('asdlkj\n')250- click.prompt('Prompt to stderr', err=True)250+ emulate_input("asdlkj\n")251+ click.prompt("Prompt to stderr", err=True)252 out, err = capfd.readouterr()252- assert out == ''253- assert err == 'Prompt to stderr: '253+ assert out == ""254+ assert err == "Prompt to stderr: "255 255- emulate_input('y\n')256- click.confirm('Prompt to stdin')256+ emulate_input("y\n")257+ click.confirm("Prompt to stdin")258 out, err = capfd.readouterr()258- assert out == 'Prompt to stdin [y/N]: '259- assert err == ''259+ assert out == "Prompt to stdin [y/N]: "260+ assert err == ""261 261- emulate_input('y\n')262- click.confirm('Prompt to stderr', err=True)262+ emulate_input("y\n")263+ click.confirm("Prompt to stderr", err=True)264 out, err = capfd.readouterr()264- assert out == ''265- assert err == 'Prompt to stderr [y/N]: '265+ assert out == ""266+ assert err == "Prompt to stderr [y/N]: "267 267- monkeypatch.setattr(click.termui, 'isatty', lambda x: True)268- monkeypatch.setattr(click.termui, 'getchar', lambda: ' ')268+ monkeypatch.setattr(click.termui, "isatty", lambda x: True)269+ monkeypatch.setattr(click.termui, "getchar", lambda: " ")270 270- click.pause('Pause to stdout')271+ click.pause("Pause to stdout")272 out, err = capfd.readouterr()272- assert out == 'Pause to stdout\n'273- assert err == ''273+ assert out == "Pause to stdout\n"274+ assert err == ""275 275- click.pause('Pause to stderr', err=True)276+ click.pause("Pause to stderr", err=True)277 out, err = capfd.readouterr()277- assert out == ''278- assert err == 'Pause to stderr\n'278+ assert out == ""279+ assert err == "Pause to stderr\n"280 281 282 def test_open_file(runner):283 @click.command()283- @click.argument('filename')284+ @click.argument("filename")285 def cli(filename):286 with click.open_file(filename) as f:287 click.echo(f.read())288 288- click.echo('meep')289+ click.echo("meep")290 291 with runner.isolated_filesystem():291- with open('hello.txt', 'w') as f:292- f.write('Cool stuff')292+ with open("hello.txt", "w") as f:293+ f.write("Cool stuff")294 294- result = runner.invoke(cli, ['hello.txt'])295+ result = runner.invoke(cli, ["hello.txt"])296 assert result.exception is None296- assert result.output == 'Cool stuff\nmeep\n'297+ assert result.output == "Cool stuff\nmeep\n"298 298- result = runner.invoke(cli, ['-'], input='foobar')299+ result = runner.invoke(cli, ["-"], input="foobar")300 assert result.exception is None300- assert result.output == 'foobar\nmeep\n'301+ assert result.output == "foobar\nmeep\n"302 303 304 def test_open_file_ignore_errors_stdin(runner):305 @click.command()32 unmodified lines338 with click.open_file("test.bin", errors="ignore") as f:339 f.read()340 341 341-@pytest.mark.skipif(WIN, reason='os.chmod() is not fully supported on Windows.')342-@pytest.mark.parametrize('permissions', [343- 0o400,344- 0o444,345- 0o600,346- 0o644,347- ])342+@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")343+@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644,])344 def test_open_file_atomic_permissions_existing_file(runner, permissions):345 with runner.isolated_filesystem():350- with open('existing.txt', 'w') as f:351- f.write('content')352- os.chmod('existing.txt', permissions)346+ with open("existing.txt", "w") as f:347+ f.write("content")348+ os.chmod("existing.txt", permissions)349 350 @click.command()355- @click.argument('filename')351+ @click.argument("filename")352 def cli(filename):357- click.open_file(filename, 'w', atomic=True).close()353+ click.open_file(filename, "w", atomic=True).close()354 359- result = runner.invoke(cli, ['existing.txt'])355+ result = runner.invoke(cli, ["existing.txt"])356 assert result.exception is None361- assert stat.S_IMODE(os.stat('existing.txt').st_mode) == permissions357+ assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions358 359 364-@pytest.mark.skipif(WIN, reason='os.stat() is not fully supported on Windows.')360+@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")361 def test_open_file_atomic_permissions_new_file(runner):362 with runner.isolated_filesystem():363+364 @click.command()368- @click.argument('filename')365+ @click.argument("filename")366 def cli(filename):370- click.open_file(filename, 'w', atomic=True).close()367+ click.open_file(filename, "w", atomic=True).close()368 369 # Create a test file to get the expected permissions for new files370 # according to the current umask.374- with open('test.txt', 'w'):371+ with open("test.txt", "w"):372 pass376- permissions = stat.S_IMODE(os.stat('test.txt').st_mode)373+ permissions = stat.S_IMODE(os.stat("test.txt").st_mode)374 378- result = runner.invoke(cli, ['new.txt'])375+ result = runner.invoke(cli, ["new.txt"])376 assert result.exception is None380- assert stat.S_IMODE(os.stat('new.txt').st_mode) == permissions377+ assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions378 379 380 def test_iter_keepopenfile(tmpdir):381 expected = list(map(str, range(10)))385- p = tmpdir.mkdir('testdir').join('testfile')382+ p = tmpdir.mkdir("testdir").join("testfile")383 p.write("\n".join(expected))384 with p.open() as f:385 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):386 assert e_line == a_line.strip()387 388 389 def test_iter_lazyfile(tmpdir):390 expected = list(map(str, range(10)))394- p = tmpdir.mkdir('testdir').join('testfile')391+ p = tmpdir.mkdir("testdir").join("testfile")392 p.write("\n".join(expected))393 with p.open() as f:394 with click.utils.LazyFile(f.name) as lf:395 for e_line, a_line in zip(expected, lf):1 unmodified linemodified:setup.py+1 added-1 removed
6 unmodified lines7 with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()9 10 with io.open("src/click/__init__.py", "rt", encoding="utf8") as f:11- version = re.search(r"__version__ = '(.*?)'", f.read()).group(1)11+ version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)12 13 setup(14 name="click",15 version=version,25 unmodified lines