Skip to content
Myr

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

57 files+3238 added−2640 removed

modified:docs/conf.py+1 added-3 removed
45 unmodified lines
46html_show_sourcelink = False4748# LaTeX ----------------------------------------------------------------4950latex_documents = [51 (master_doc, f"Click-{version}.tex", html_title, author, "manual")52]50latex_documents = [(master_doc, f"Click-{version}.tex", html_title, author, "manual")]
modified:examples/aliases/aliases.py+26 added-20 removed
20 unmodified lines
21 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 pass2829 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)363738pass_config = click.make_pass_decorator(Config, ensure=True)
22 unmodified lines
61 # 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)))737475def read_config(ctx, param, value):76 """Callback that is used whenever --config is passed. We use this to
2 unmodified lines
79 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 value868788@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)96def cli():97 """An example application that supports aliases."""9899100@cli.command()101def push():102 """Pushes changes."""98 click.echo('Push')103 click.echo("Push")104105106@cli.command()107def pull():108 """Pulls changes."""104 click.echo('Pull')109 click.echo("Pull")110111112@cli.command()113def clone():114 """Clones a repository."""110 click.echo('Clone')115 click.echo("Clone")116117118@cli.command()119def commit():120 """Commits pending changes."""116 click.echo('Commit')121 click.echo("Commit")122123124@cli.command()125@pass_config126def status(config):127 """Shows the status."""123 click.echo('Status for %s' % config.path)128 click.echo("Status for %s" % config.path)129130131@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)138def 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
1from setuptools import setup23setup(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 lines
14 if incomplete in key:15 yield key161718@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)20def 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])232425@click.group(help='A group that holds a subcommand')25@click.group(help="A group that holds a subcommand")26def group():27 pass282930def 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]]363740@group.command(help='Choose a user')38@group.command(help="Choose a user")39@click.argument("user", type=click.STRING, autocompletion=list_users)40def subcmd(user):43 click.echo('Chosen user is %s' % user)41 click.echo("Chosen user is %s" % user)424344cli.add_command(group)
modified:examples/bashcompletion/setup.py+6 added-8 removed
1from setuptools import setup23setup(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
1import click234all_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'4all_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)222324@click.command()25def cli():
3 unmodified lines
2930 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 )4027 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
1from setuptools import setup23setup(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 line
23import click456@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_environment9def 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 line
23import click456@click.command('status', short_help='Shows file changes.')6@click.command("status", short_help="Shows file changes.")7@pass_environment8def 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 lines
34import click567CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')7CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")8910class Environment(object):1111 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()14
9 unmodified lines
24 self.log(msg, *args)252627pass_environment = click.make_pass_decorator(Environment, ensure=True)29cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),30 'commands'))28cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))293031class ComplexCLI(click.MultiCommand):3432 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 rv3940 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.cli484950@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_environment58def cli(ctx, verbose, home):59 """A complex command line interface."""60 ctx.verbose = verbose
2 unmodified lines
modified:examples/complex/setup.py+6 added-8 removed
1from setuptools import setup23setup(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 lines
42def processor(f):43 """Helper decorator to rewrite a function so that it returns another44 function from it.45 """4647 def new_func(*args, **kwargs):48 def processor(stream):49 return f(stream, *args, **kwargs)5051 return processor5253 return update_wrapper(new_func, f)545556def generator(f):57 """Similar to the :func:`processor` but passes through old values58 unchanged and does not pass through the values as parameter.59 """6061 @processor62 def new_func(stream, *args, **kwargs):63 for item in stream:64 yield item65 for item in f(*args, **kwargs):66 yield item6768 return update_wrapper(new_func, f)697071def copy_filename(new, old):72 new.filename = old.filename73 return new747571@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@generator86def 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)10110292@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@processor112def save_cmd(images, filename):113 """Saves all processed images to a series of files."""114 for idx, image in enumerate(images):
1 unmodified line
116 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)121122109@cli.command('display')123@cli.command("display")124@processor125def display_cmd(images):126 """Opens all images in an image viewer."""127 for image in images:
1 unmodified line
129 image.show()130 yield image131132119@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@processor137def resize_cmd(images, width, height):138 """Resizes an image by fitting it into the box without changing139 the aspect ratio.
4 unmodified lines
144 image.thumbnail((w, h))145 yield image146147134@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@processor153def crop_cmd(images, border):154 """Crops an image from all edges."""155 for image in images:
11 unmodified lines
167def 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)178179180def 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)189190176@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@processor197def transpose_cmd(images, rotate, flip):198 """Transposes an image by either rotating or flipping it."""199 for image in images:
7 unmodified lines
207 image = copy_filename(image.transpose(mode), image)208 yield image209210196@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@processor214def blur_cmd(images, radius):215 """Applies gaussian blur."""216 blur = ImageFilter.GaussianBlur(radius)
1 unmodified line
218 click.echo('Blurring "%s" by %dpx' % (image.filename, radius))219 yield copy_filename(image.filter(blur), image)220221208@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@processor231def 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 image241242222@cli.command('emboss')243@cli.command("emboss")244@processor245def 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)250251231@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@processor257def sharpen_cmd(images, factor):258 """Sharpens an image."""259 for image in images:
1 unmodified line
261 enhancer = ImageEnhance.Sharpness(image)262 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)263264243@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@processor269def paste_cmd(images, left, right):270 """Pastes the second image on the first image and leaves the rest271 unchanged.
6 unmodified lines
278 if image is not None:279 yield image280 return281260 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 image289290 for image in imageiter:291 yield image
modified:examples/imagepipe/setup.py+6 added-9 removed
1from setuptools import setup23setup(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
1import click234@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"))7def 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 lines
modified:examples/inout/setup.py+6 added-8 removed
1from setuptools import setup23setup(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 lines
16def ship():17 """Manages ships."""181920@ship.command('new')21@click.argument('name')20@ship.command("new")21@click.argument("name")22def ship_new(name):23 """Creates a new ship."""24 click.echo('Created ship %s' % name)24 click.echo("Created ship %s" % name)252627@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.")32def 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))353638@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)41def 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))444547@cli.group('mine')46@cli.group("mine")47def mine():48 """Manages mines."""495052@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.")62def 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))656665@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)70def 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
1from setuptools import setup23setup(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 lines
5import click678class Repo(object):99 def __init__(self, home):10 self.home = home11 self.config = {}12 self.verbose = False1314 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)1819 def __repr__(self):21 return '<Repo %r>' % self.home20 return "<Repo %r>" % self.home212223pass_repo = click.make_pass_decorator(Repo)242526@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_context44def 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 lines
57 ctx.obj.set_config(key, value)585960@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_repo72def clone(repo, src, dest, shallow, rev):73 """Clones a repository.74
1 unmodified line
76 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)868788@cli.command()89@click.confirmation_option()
2 unmodified lines
92 """Deletes a repository.9394 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!")9899100@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_repo105def setuser(repo, username, email, password):106 """Sets the user credentials.107108 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.")114115116@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_repo126def commit(repo, files, message):127 """Commits outstanding changes.128
3 unmodified lines
132 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)152153140@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_repo161def 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
1from setuptools import setup23setup(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
1from setuptools import setup23setup(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 lines
1415@cli.command()16def 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))212223@cli.command()24def 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))303132@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)39def progress(count):40 """Demonstrates the progress bar."""41 items = range(count)42
4 unmodified lines
47 for item in items:48 if random.random() > 0.3:49 yield item5047 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)5657 def show_item(item):58 if item is not None:54 return 'Item #%d' % item59 return "Item #%d" % item6056 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)6962 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)7969 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)8990 # '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)102103104@cli.command()87@click.argument('url')105@click.argument("url")106def open(url):107 """Opens a file or URL In the default application."""108 click.launch(url)109110111@cli.command()94@click.argument('url')112@click.argument("url")113def locate(url):114 """Opens a file or URL In the default application."""115 click.launch(url, locate=True)116117118@cli.command()119def 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!")131132133@cli.command()134def clear():
9 unmodified lines
144145@cli.command()146def 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 return
modified:examples/validation/setup.py+6 added-8 removed
1from setuptools import setup23setup(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 lines
789def 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 value131415class URL(click.ParamType):16 name = 'url'16 name = "url"1718 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 value293031@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()38def cli(count, foo, url):39 """Validation.4041 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 lines
75# Controls if click should emit the warning about the use of unicode76# literals.77disable_unicode_literals_warning = False7879__version__ = '7.1.dev'79__version__ = "7.1.dev"
modified:src/click/_bashcomplete.py+72 added-43 removed
12 unmodified lines
13 from collections import abc14except ImportError:15 import collections as abc1617WORDBREAK = '='17WORDBREAK = "="1819# Note, only BASH version 4.4 and later have the nosort option.20COMPLETION_SCRIPT_BASH = '''20COMPLETION_SCRIPT_BASH = """21%(complete_func)s() {22 local IFS=$'\n'23 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\24 COMP_CWORD=$COMP_CWORD \\
12 unmodified lines
37 complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s38}3940%(complete_func)setup41'''41"""4243COMPLETION_SCRIPT_ZSH = '''43COMPLETION_SCRIPT_ZSH = """44#compdef %(script_names)s4546%(complete_func)s() {47 local -a completions
24 unmodified lines
72 compstate[insert]="automenu"73}7475compdef %(complete_func)s %(script_names)s76'''76"""7778COMPLETION_SCRIPT_FISH = '''78COMPLETION_SCRIPT_FISH = """79complete --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"""8182_completion_scripts = {83 "bash": COMPLETION_SCRIPT_BASH,84 "zsh": COMPLETION_SCRIPT_ZSH,85 "fish": COMPLETION_SCRIPT_FISH,86}8788_invalid_ident_char_re = re.compile(r'[^a-zA-Z0-9_]')88_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")899091def 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() + ";"102103104def resolve_ctx(cli, prog_name, args):105 """
10 unmodified lines
116 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 lines
147 """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] == "-"152153154def is_incomplete_option(all_args, cmd_param):155 """
7 unmodified lines
163 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_str
14 unmodified lines
188 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 False199200
7 unmodified lines
208 """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 results223224225def get_visible_commands_starting_with(ctx, starts_with):
12 unmodified lines
238def 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 )247248 # 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 )260261262def get_choices(cli, prog_name, args, incomplete):263 """
17 unmodified lines
281 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 = ""286287 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 lines
312 return sorted(completions)313314315def 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 = ""323324 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 "_")331332 return True333334
31 unmodified lines
modified:src/click/_compat.py+121 added-103 removed
4 unmodified lines
5import sys6from weakref import WeakKeyDictionary78PY2 = sys.version_info[0] == 29CYGWIN = sys.platform.startswith('cygwin')10MSYS2 = sys.platform.startswith('win') and ('GCC' in sys.version)9CYGWIN = sys.platform.startswith("cygwin")10MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)11# Determine local App Engine environment, per Google's own suggestion12APP_ENGINE = ('APPENGINE_RUNTIME' in os.environ and13 'Development/' in os.environ.get('SERVER_SOFTWARE', ''))14WIN = sys.platform.startswith('win') and not APP_ENGINE and not MSYS212APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(13 "SERVER_SOFTWARE", ""14)15WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS216DEFAULT_COLUMNS = 80171819_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
2 unmodified lines
22def get_filesystem_encoding():23 return sys.getfilesystemencoding() or sys.getdefaultencoding()242525def _make_text_stream(stream, encoding, errors,26 force_readable=False, force_writable=False):26def _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 )414243def 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 False495051def 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 rv575859class _NonClosingTextIOWrapper(io.TextIOWrapper):5455 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)7172 # 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:7677 def write(self, x):78 if isinstance(x, str) or is_bytes(x):79 try:80 self.flush()
35 unmodified lines
116 def __getattr__(self, name):117 return getattr(self._stream, name)118119 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 implementation
4 unmodified lines
129130 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 lines
141142 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 True156157 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 lines
177178 def is_bytes(x):179 return isinstance(x, (buffer, bytearray))180169 _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_]*$")182183 # 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 to
19 unmodified lines
205 import msvcrt206 except ImportError:207 pass208 else:209210 def set_binary_mode(f):211 try:212 fileno = f.fileno()213 except Exception:
6 unmodified lines
220 import fcntl221 except ImportError:222 pass223 else:224225 def set_binary_mode(f):226 try:227 fileno = f.fileno()228 except Exception:
9 unmodified lines
238 def get_binary_stdin():239 return set_binary_mode(sys.stdin)240241 def get_binary_stdout():228 _wrap_std_stream('stdout')242 _wrap_std_stream("stdout")243 return set_binary_mode(sys.stdout)244245 def get_binary_stderr():232 _wrap_std_stream('stderr')246 _wrap_std_stream("stderr")247 return set_binary_mode(sys.stderr)248249 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)254255 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)261262 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)268269 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 value273274275else:276 import io277278 text_type = str279 raw_input = input280 string_types = (str,)281 int_types = (int,)
15 unmodified lines
297 # closed. In this case, we assume the default.298299 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 default
6 unmodified lines
315 # we need to deal with this case explicitly.316 if _is_binary_reader(stream, False):317 return stream318305 buf = getattr(stream, 'buffer', None)319 buf = getattr(stream, "buffer", None)320321 # 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 lines
330 # we need to deal with this case explicitly.331 if _is_binary_writer(stream, False):332 return stream333320 buf = getattr(stream, 'buffer', None)334 buf = getattr(stream, "buffer", None)335336 # 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 lines
343 # 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")348349 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 attribute
5 unmodified lines
357 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)364365 def _force_correct_text_stream(366 text_stream,367 encoding,
7 unmodified lines
375 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_stream383384 # Otherwise, get the underlying binary reader.
41 unmodified lines
426427 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 reader434435 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 writer442443 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 writer450451 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 )458459 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 )466467 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 )474475 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 value481482483def 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 msg494495496def _wrap_io_open(file, mode, encoding, errors):
17 unmodified lines
514 f = io.open(file, "b" + mode.replace("t", ""))515 return _make_text_stream(f, **kwargs)516517504def open_stream(filename, mode='r', encoding=None, errors='strict', atomic=False):518def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):519 binary = "b" in mode520521 # 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 lines
533 if not atomic:534 return _wrap_io_open(filename, mode, encoding, errors), True535536 # 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.")548549 # 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 an
8 unmodified lines
560561 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL562563 if binary:550 flags |= getattr(os, 'O_BINARY', 0)564 flags |= getattr(os, "O_BINARY", 0)565566 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 break
14 unmodified lines
588 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True589590591# Used in a destructor call, needs extra protection from interpreter cleanup.578if hasattr(os, 'replace'):592if hasattr(os, "replace"):593 _replace = os.replace594 _can_replace = True595else:596 _replace = os.rename597 _can_replace = not WIN598599600class _AtomicFile(object):587601 def __init__(self, f, tmp_filename, real_filename):602 self._f = f603 self._tmp_filename = tmp_filename604 self._real_filename = real_filename
33 unmodified lines
638get_winterm_size = None639640641def strip_ansi(value):629 return _ansi_re.sub('', value)642 return _ansi_re.sub("", value)643644645def _is_jupyter_kernel_output(stream):646 if WIN:
25 unmodified lines
672 from ._winconsole import _get_windows_console_stream, _wrap_std_stream673674 def _get_argv_encoding():675 import locale676677 return locale.getpreferredencoding()678679 if PY2:680666 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")688689 try:690 import colorama691 except ImportError:
33 unmodified lines
725 return rv726727 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.Top732733734else:735736 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()738739 _get_windows_console_stream = lambda *x: None740 _wrap_std_stream = lambda *x: None741
10 unmodified lines
752753754def _make_cached_stream_func(src_func, wrapper_func):755 cache = WeakKeyDictionary()756757 def func():758 stream = src_func()759 try:760 rv = cache.get(stream)
7 unmodified lines
768 cache[stream] = rv769 except Exception:770 pass771 return rv772773 return func774775755_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)779780781binary_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}786787text_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 lines
23from ._compat import WIN24from .exceptions import ClickException25from .utils import echo2627if os.name == 'nt':28 BEFORE_BAR = '\r'29 AFTER_BAR = '\n'27if os.name == "nt":28 BEFORE_BAR = "\r"29 AFTER_BAR = "\n"30else:31 BEFORE_BAR = '\r\033[?25l'32 AFTER_BAR = '\033[?25h\n'31 BEFORE_BAR = "\r\033[?25l"32 AFTER_BAR = "\033[?25h\n"333435def _length_hint(obj):36 """Returns the length hint of an object."""
7 unmodified lines
44 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 hint515253class ProgressBar(object):5657 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 = color
3 unmodified lines
87 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 None
18 unmodified lines
114 self.render_finish()115116 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()121122 def __next__(self):
44 unmodified lines
167 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 ""175176 def format_pos(self):177 pos = str(self.pos)178 if self.length_known:169 pos += '/%s' % self.length179 pos += "/%s" % self.length180 return pos181182 def format_pct(self):173 return ('% 4d%%' % int(self.pct * 100))[1:]183 return ("% 4d%%" % int(self.pct * 100))[1:]184185 def format_bar(self):186 if self.length_known:187 bar_length = int(self.pct * self.width)
3 unmodified lines
191 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 bar203204 def format_progress_line(self):205 show_percent = self.show_percent
12 unmodified lines
218 item_info = self.item_show_func(self.current_item)219 if item_info is not None:220 info_bits.append(item_info)221208 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()230231 def render_progress(self):232 from .termui import get_terminal_size233
8 unmodified lines
242 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_width249250 clear_width = self.width
6 unmodified lines
257 if self.max_width is None or self.max_width < line_len:258 self.max_width = line_len259260 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.264265 if line != self._last_line and not self.is_fast():266 self._last_line = line
43 unmodified lines
310 # `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.")315316 if self.is_hidden:317 for rv in self.iter:318 yield rv
10 unmodified lines
329 """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)344345 import tempfile346347 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 lines
358 """Page through text by feeding it to another program. Invoking a359 pager through this might support colors.360 """361 import subprocess362363 env = dict(os.environ)364365 # 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 = True375357 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)382365 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 lines
405406def _tempfilepager(generator, cmd, color):407 """Page through text by invoking a program on a temporary file."""408 import tempfile409410 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 lines
429 stream.write(text)430431432class Editor(object):414415 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 = extension438439 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"452453 def edit_file(self, filename):454 import subprocess455456 editor = self.get_editor()457 if self.env:458 environ = os.environ.copy()459 environ.update(self.env)
2 unmodified lines
462 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))473474 def edit(self, text):475 import tempfile476459 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"480463 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)489472 f = os.fdopen(fd, 'wb')490 f = os.fdopen(fd, "wb")491 f.write(text)492 f.close()493 timestamp = os.path.getmtime(name)494495 self.edit_file(name)496479 if self.require_save \480 and os.path.getmtime(name) == timestamp:497 if self.require_save and os.path.getmtime(name) == timestamp:498 return None499483 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)508509
4 unmodified lines
514 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 url521505 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 lines
547 return os.system(args)548549 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 webbrowser561562 webbrowser.open(url)563 return 0564 return 1565566567def _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()574575576if WIN:
38 unmodified lines
615 else:616 func = msvcrt.getwch617618 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 rv625626627else:628 import tty629 import termios630631 @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 = None
12 unmodified lines
651652 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 ch
modified:src/click/_textwrap.py+1 added-2 removed
1 unmodified line
2from contextlib import contextmanager345class TextWrapper(textwrap.TextWrapper):66 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):7 space_left = max(width - cur_len, 1)89 if self.break_long_words:
23 unmodified lines
33 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 lines
7# 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.11click = sys.modules[__name__.rsplit('.', 1)[0]]11click = sys.modules[__name__.rsplit(".", 1)[0]]121314def _find_unicode_literals_frame():15 import __future__1616 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 idx
10 unmodified lines
37 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)4142 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 )535455def _verify_python3_env():56 """Ensures that the environment is good for unicode on Python 3."""57 if PY2:58 return59 try:60 import locale6162 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 return6761 extra = ''62 if os.name == 'posix':68 extra = ""69 if os.name == "posix":70 import subprocess7172 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 = False8081 # 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")8485 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 = True9183 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))113114 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_locale127128 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 lines
37from ._compat import text_type3839try:40 from ctypes import pythonapi4142 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer43 PyBuffer_Release = pythonapi.PyBuffer_Release44except ImportError:45 pythonapi = None
6 unmodified lines
52ReadConsoleW = kernel32.ReadConsoleW53WriteConsoleW = kernel32.WriteConsoleW54GetConsoleMode = kernel32.GetConsoleMode55GetLastError = kernel32.GetLastError55GetCommandLineW = WINFUNCTYPE(LPWSTR)(56 ('GetCommandLineW', windll.kernel32))57CommandLineToArgvW = WINFUNCTYPE(58 POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(59 ('CommandLineToArgvW', windll.shell32))56GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))57CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(58 ("CommandLineToArgvW", windll.shell32)59)60LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(61 ('LocalFree', windll.kernel32))61 ("LocalFree", windll.kernel32)62)636465STDIN_HANDLE = GetStdHandle(-10)66STDOUT_HANDLE = GetStdHandle(-11)
10 unmodified lines
77STDIN_FILENO = 078STDOUT_FILENO = 179STDERR_FILENO = 28080EOF = b'\x1a'81EOF = b"\x1a"82MAX_BYTES_WRITTEN = 32767838485class 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 ]99100 if PY2:100 _fields_.insert(-1, ('smalltable', c_ssize_t * 2))101 _fields_.insert(-1, ("smalltable", c_ssize_t * 2))102103104# On PyPy we cannot get buffers so our ability to operate here is105# serverly limited.106if pythonapi is None:107 get_buffer = None108else:109110 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 lines
118 PyBuffer_Release(byref(buf))119120121class _WindowsConsoleRawIOBase(io.RawIOBase):120122 def __init__(self, handle):123 self.handle = handle124125 def isatty(self):
1 unmodified line
127 return True128129130class _WindowsConsoleReader(_WindowsConsoleRawIOBase):130131 def readable(self):132 return True133134 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 )142143 buffer = get_buffer(b, writable=True)144 code_units_to_be_read = bytes_to_be_read // 2145 code_units_read = c_ulong()146146 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())159160 if buffer[0] == EOF:161 return 0162 return 2 * code_units_read.value163164165class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):160166 def writable(self):167 return True168169 @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" % errno176177 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()182183 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.value191192 if bytes_written == 0 and bytes_to_be_written > 0:193 raise OSError(self._get_error_message(GetLastError()))194 return bytes_written195196197class ConsoleStream(object):189198 def __init__(self, text_stream, byte_stream):199 self._text_stream = text_stream200 self.buffer = byte_stream201
20 unmodified lines
222 def isatty(self):223 return self.buffer.isatty()224225 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,)227228229class 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 """235236 def __init__(self, wrapped):237 # double-underscore everything to prevent clashes with names of238 # attributes on the wrapped stream object.239 self.__wrapped = wrapped
6 unmodified lines
246 written = 0247248 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_write252253254_wrapped_std_streams = set()255256257def _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)266267268def _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)276277278def _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)286287288def _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)296297298if PY2:299300 def _hash_py_argv():281 return zlib.crc32('\x00'.join(sys.argv[1:]))301 return zlib.crc32("\x00".join(sys.argv[1:]))302303 _initial_argv_hash = _hash_py_argv()304305 def _get_windows_argv():
6 unmodified lines
312 finally:313 LocalFree(argv_unicode)314 del argv_unicode315296 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 break325326 return argv[1:]327
5 unmodified lines
333}334335336def _is_console(f):317 if not hasattr(f, 'fileno'):337 if not hasattr(f, "fileno"):338 return False339340 try:341 fileno = f.fileno()
4 unmodified lines
346 return bool(GetConsoleMode(handle, byref(DWORD())))347348349def _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 we
5 unmodified lines
modified:src/click/core.py+321 added-194 removed
36 unmodified lines
37from .utils import PacifyFlushWrapper3839_missing = object()4041SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'42SUBCOMMANDS_METAVAR = 'COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]...'41SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."42SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."4344DEPRECATED_HELP_NOTICE = ' (DEPRECATED)'45DEPRECATED_INVOKE_NOTICE = 'DeprecationWarning: ' + \46 'The command %(name)s is deprecated.'44DEPRECATED_HELP_NOTICE = " (DEPRECATED)"45DEPRECATED_INVOKE_NOTICE = (46 "DeprecationWarning: " + "The command %(name)s is deprecated."47)484950def _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)535455def fast_exit(code):56 """Exit without garbage collection, this speeds up exit by about 10ms for
6 unmodified lines
6364def _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 return7172 from ._bashcomplete import bashcomplete7374 if bashcomplete(cmd, prog_name, complete_var, complete_instr):75 fast_exit(1)767778def _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 )106107108def batch(iterable, batch_size):109 return list(zip(*repeat(iter(iterable), batch_size)))110111112def 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)115116 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)119120 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)130131
20 unmodified lines
152 """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 """156157 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)163164 return sorted(declaration_order, key=sort_key)165
83 unmodified lines
249 Even if an option is later created with show_default=False,250 this command-level setting overrides it.251 """252234 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 = command
12 unmodified lines
288 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", {})293294 #: 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_map302303 #: This flag indicates if a subcommand is going to be executed. A
50 unmodified lines
354 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"]359360 #: The names for the help options.361 self.help_option_names = help_option_names362
12 unmodified lines
375 # 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 lines
480 return self._meta481482 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 )487488 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 bind
17 unmodified lines
508 """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()518519 def find_root(self):520 """Finds the outermost context."""
83 unmodified lines
604 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 )611612 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 lines
627628 # 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.")632633 for param in self.params:634 if param not in kwargs:635 kwargs[param] = self.params[param]
21 unmodified lines
657 :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 """661662 #: 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 = True
14 unmodified lines
680 def __repr__(self):681 return "<%s %s>" % (self.__class__.__name__, self.name)682683 def get_usage(self, ctx):644 raise NotImplementedError('Base commands cannot get usage')684 raise NotImplementedError("Base commands cannot get usage")685686 def get_help(self, ctx):647 raise NotImplementedError('Base commands cannot get help')687 raise NotImplementedError("Base commands cannot get help")688689 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 not
21 unmodified lines
713 """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 )720721 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")726686 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 lines
777 else:778 args = list(args)779780 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__))782783 # Hook for the Bash completion. This only activates if the Bash784 # completion is actually enabled, otherwise this is quite a fast785 # noop.
43 unmodified lines
829 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)835836 def __call__(self, *args, **kwargs):837 """Alias for :meth:`main`."""
32 unmodified lines
870 :param deprecated: issues a message indicating that871 the command is deprecated.872 """873828 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 = callback
2 unmodified lines
895 #: 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_help
8 unmodified lines
913 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")918919 def get_params(self, ctx):920 rv = self.params921 help_option = self.get_help_option(ctx)
6 unmodified lines
928929 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))933934 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 lines
957 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.')961962 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 )970971 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 lines
981 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")986987 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 )995996 def format_help(self, ctx, formatter):997 """Writes the help into the formatter if it exists.998
33 unmodified lines
1032 if rv is not None:1033 opts.append(rv)10341035 if opts:969 with formatter.section('Options'):1036 with formatter.section("Options"):1037 formatter.write_dl(opts)10381039 def format_epilog(self, ctx, formatter):1040 """Writes the epilog into the formatter if it exists."""
9 unmodified lines
10501051 parser = self.make_parser(ctx)1052 opts, args, param_order = parser.parse_args(args=args)1053987 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)10561057 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 )10621063 ctx.args = args1064 return args1065
28 unmodified lines
1094 multiple commands to be chained together.1095 :param result_callback: the result callback to attach to this multi1096 command.1097 """10981099 allow_extra_args = True1100 allow_interspersed_args = False11011034 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_help
11 unmodified lines
11271128 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 )11351136 def collect_usage_pieces(self, ctx):1137 rv = Command.collect_usage_pieces(self, ctx)1138 rv.append(self.subcommand_metavar)
27 unmodified lines
11661167 :param replace: if set to `True` an already existing result1168 callback will be removed.1169 """11701171 def decorator(f):1172 old_callback = self.result_callback1173 if old_callback is None or replace:1174 self.result_callback = f1175 return f11761177 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)11791180 self.result_callback = rv = update_wrapper(function, f)1181 return rv11821183 return decorator11841185 def format_commands(self, ctx, formatter):1186 """Extra format methods for multi methods that adds all the commands
19 unmodified lines
1206 help = cmd.get_short_help_str(limit)1207 rows.append((subcommand, help))12081209 if rows:1130 with formatter.section('Commands'):1210 with formatter.section("Commands"):1211 formatter.write_dl(rows)12121213 def parse_args(self, ctx, args):1214 if not args and self.no_args_is_help and not ctx.resilient_parsing:
11 unmodified lines
12261227 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 value12321233 if not ctx.protected_args:1234 # If we are invoked without command the chain flag controls
7 unmodified lines
1242 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.")12471248 # Fetch args back out1249 args = ctx.protected_args + ctx.args1250 ctx.args = []
18 unmodified lines
1269 # 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)12751276 # 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, []12911292 rv = []
58 unmodified lines
1351 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] = cmd13581359 def command(self, *args, **kwargs):
1 unmodified line
1361 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 """13651366 def decorator(f):1367 cmd = command(*args, **kwargs)(f)1368 self.add_command(cmd)1369 return cmd13701371 return decorator13721373 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 """13791380 def decorator(f):1381 cmd = group(*args, **kwargs)(f)1382 self.add_command(cmd)1383 return cmd13841385 return decorator13861387 def get_command(self, ctx, cmd_name):1388 return self.commands.get(cmd_name)
78 unmodified lines
1467 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"14721386 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 )14901491 self.type = convert_type(type, default)14921493 # Default nargs to what the type tells us if we have that
31 unmodified lines
1525 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 metavar15311532 def get_default(self, ctx):1533 """Given a context variable this calculates the default value."""
21 unmodified lines
1555 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)15681569 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 ())15731574 return _convert(value, (self.nargs != 1) + bool(self.multiple))15751576 def process_value(self, ctx, value):1577 """Given a value and context this runs the logic to convert the
54 unmodified lines
1632 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 lines
1652 """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)165716581659class Option(Parameter):1660 """Options are usually optional values on the command line and
32 unmodified lines
1693 context.1694 :param help: the help string.1695 :param hidden: hide this option from help outputs.1696 """1597 param_type_name = 'option'16971599 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"16991700 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)17211722 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 = prompt
13 unmodified lines
1741 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 = False
15 unmodified lines
17651766 # 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 )17871788 def _parse_decls(self, decls, expose_value):1789 opts = []1790 secondary_opts = []
2 unmodified lines
17931794 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 lines
1812 opts.append(decl)18131814 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 = None18191820 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")18241825 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 )18311832 return name, opts, secondary_opts18331834 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 }18401841 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"18471848 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)18641865 def get_help_record(self, ctx):1866 if self.hidden:
4 unmodified lines
1871 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 rv18771878 rv = [_write_opts(self.opts)]1879 if self.secondary_opts:1880 rv.append(_write_opts(self.secondary_opts))18811763 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))19081909 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))19131793 return ((any_prefix_is_slash and '; ' or ' / ').join(rv), help)1914 return ((any_prefix_is_slash and "; " or " / ").join(rv), help)19151916 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 out
19 unmodified lines
1938 # differently.1939 if self.is_bool_flag:1940 return confirm(self.prompt, default)19411942 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 )19511952 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)19591960 def value_from_envvar(self, ctx):1961 rv = self.resolve_envvar_value(ctx)
6 unmodified lines
1968 rv = batch(rv, self.nargs)1969 return rv19701971 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)19751976
3 unmodified lines
1980 and are required by default.19811982 All parameters are passed onwards to the parameter constructor.1983 """1860 param_type_name = 'argument'19841985 param_type_name = "argument"19861987 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 )19981999 @property2000 def human_readable_name(self):2001 if self.metavar is not None:
6 unmodified lines
2008 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 var20162017 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], []20312032 def get_usage_pieces(self, ctx):2033 return [self.make_metavar()]
1 unmodified line
2035 def get_error_hint(self, ctx):2036 return '"%s"' % self.make_metavar()20372038 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)204020412042# Circular dependency between decorators and core2043from .decorators import command, group
modified:src/click/decorators.py+72 added-49 removed
10 unmodified lines
11def pass_context(f):12 """Marks a callback as wanting to receive the current context13 object as first argument.14 """1516 def new_func(*args, **kwargs):17 return f(get_current_context(), *args, **kwargs)1819 return update_wrapper(new_func, f)202122def 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 """2728 def new_func(*args, **kwargs):29 return f(get_current_context().obj, *args, **kwargs)3031 return update_wrapper(new_func, f)323334def make_pass_decorator(object_type, ensure=False):
17 unmodified lines
52 :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 """5657 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)7071 return update_wrapper(new_func, f)7273 return decorator747576def _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 )100101102def command(name=None, cls=None, **attrs):103 r"""Creates a new :class:`Command` and uses the decorated function as
16 unmodified lines
120 :class:`Command`.121 """122 if cls is None:123 cls = Command124125 def decorator(f):126 cmd = _make_command(f, name, attrs, cls)127 cmd.__doc__ = f.__doc__128 return cmd129130 return decorator131132133def 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)140141142def _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)149150
6 unmodified lines
157158 :param cls: the argument class to instantiate. This defaults to159 :class:`Argument`.160 """161162 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 f166167 return decorator168169170def option(*param_decls, **attrs):
5 unmodified lines
176177 :param cls: the option class to instantiate. This defaults to178 :class:`Option`.179 """180181 def decorator(f):182 # Issue 926, copy attrs, so pre-defined options can re-use the same cls=183 option_attrs = attrs.copy()184169 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 f190191 return decorator192193194def confirmation_option(*param_decls, **attrs):
12 unmodified lines
207 expose_value=False, prompt='Do you want to continue?')208 def dropdb():209 pass210 """211212 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)216217 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)223224 return decorator225226227def password_option(*param_decls, **attrs):
7 unmodified lines
235 hide_input=True)236 def changeadmin(password):237 pass238 """239240 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)245246 return decorator247248249def version_option(version=None, *param_decls, **attrs):
8 unmodified lines
258 (``'%(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 = ""266267 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")270271 def callback(ctx, param, value):272 if not value or ctx.resilient_parsing:273 return
7 unmodified lines
281 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()294276 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)301302 return decorator303304305def help_option(*param_decls, **attrs):
5 unmodified lines
311 prints in the callback and exits.312313 All arguments are forwarded to :func:`option`.314 """315316 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)321322 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)328329 return decorator330331332# Circular dependencies between core and decorators
1 unmodified line
modified:src/click/exceptions.py+32 added-30 removed
4 unmodified lines
567def _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_hint111213class ClickException(Exception):
5 unmodified lines
19 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 = message2627 def format_message(self):
5 unmodified lines
33 if PY2:34 __unicode__ = __str__3536 def __str__(self):37 return self.message.encode('utf-8')37 return self.message.encode("utf-8")3839 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)434445class UsageError(ClickException):46 """An internal exception that signals a usage error. This typically
2 unmodified lines
49 :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 """5354 exit_code = 25556 def __init__(self, message, ctx=None):57 ClickException.__init__(self, message)
3 unmodified lines
61 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)757677class BadParameter(UsageError):78 """An exception that formats out a standardized error message for a
12 unmodified lines
91 a string it's used as such, if it's a list then92 each item is quoted and separated.93 """9493 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 lines
102 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)108108 return 'Invalid value for %s: %s' % (param_hint, self.message)109 return "Invalid value for %s: %s" % (param_hint, self.message)110111112class MissingParameter(BadParameter):113 """Raised if click required an option or argument but it was not
6 unmodified lines
120 the given `param`. Valid values are ``'parameter'``,121 ``'option'`` or ``'argument'``.122 """123123 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_type129130 def format_message(self):
13 unmodified lines
144 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_extra151150 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 )158159 def __str__(self):160 if self.message is None:
15 unmodified lines
176177 .. versionadded:: 4.0178 """179178 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 = possibilities186187 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)196197198class BadOptionUsage(UsageError):199 """Raised if an option is generally supplied but the use of the option
27 unmodified lines
227228 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 = filename235236 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)238239240class Abort(RuntimeError):241 """An internal signalling exception that signals Click to abort."""
4 unmodified lines
246 status code.247248 :param code: the status code to exit with.249 """250251 def __init__(self, code=0):252 self.exit_code = code
modified:src/click/formatting.py+60 added-43 removed
17 unmodified lines
1819def 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))232425def wrap_text(text, width=78, initial_indent='', subsequent_indent='',26 preserve_paragraphs=False):25def 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 lines
43 :param preserve_paragraphs: if this flag is set then the wrapping will44 intelligently handle paragraphs.45 """46 from ._textwrap import TextWrapper4748 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)5758 p = []
2 unmodified lines
6162 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[:]7071 for line in text.splitlines():72 if not line:
8 unmodified lines
81 _flush_par()8283 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))9086 return '\n\n'.join(rv)91 return "\n\n".join(rv)929394class HelpFormatter(object):95 """This class helps with formatting text-based help pages. It's
30 unmodified lines
126 def dedent(self):127 """Decreases the indentation."""128 self.current_indent -= self.indent_increment129125 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.132133 :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_indent139140 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 )161150 self.write('\n')162 self.write("\n")163164 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))167168 def write_paragraph(self):169 """Writes a paragraph into the buffer."""170 if self.buffer:159 self.write('\n')171 self.write("\n")172173 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")189190 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 lines
198 """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")203204 first_col = min(widths[0], col_max) + col_spacing205206 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))216217 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()220221 if lines:205 self.write(lines[0] + '\n')222 self.write(lines[0] + "\n")223224 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))226227 if len(lines) > 1:228 # separate long help from next option229 self.write("\n")230 else:214 self.write('\n')231 self.write("\n")232233 @contextmanager234 def section(self, name):235 """Helpful context manager that writes a paragraph, a heading,
19 unmodified lines
255 self.dedent()256257 def getvalue(self):258 """Returns the buffer contents."""242 return ''.join(self.buffer)259 return "".join(self.buffer)260261262def join_options(options):263 """Given a list of option strings this joins them in the most appropriate
4 unmodified lines
268 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))275276 rv.sort(key=lambda x: x[0])277261 rv = ', '.join(x[1] for x in rv)278 rv = ", ".join(x[1] for x in rv)279 return rv, any_prefix_is_slash
modified:src/click/globals.py+3 added-3 removed
17 unmodified lines
18 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.")262728def 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)313233def pop_context():34 """Removes the top level from the stack."""
13 unmodified lines
modified:src/click/parser.py+36 added-40 removed
62 unmodified lines
63 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)7071 # 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 :])7778 return tuple(rv), list(args)798081def _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))858687def 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 lines
102103def 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 pass
1 unmodified line
119 return rv120121122class Option(object):122123 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()127128 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)138139 if action is None:141 action = 'store'140 action = "store"141142 self.dest = dest143 self.action = action144 self.nargs = nargs
1 unmodified line
146 self.obj = obj147148 @property149 def takes_value(self):151 return self.action in ('store', 'append')150 return self.action in ("store", "append")151152 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)166167168class Argument(object):170169 def __init__(self, dest, nargs=1, obj=None):170 self.dest = dest171 self.nargs = nargs172 self.obj = obj
3 unmodified lines
176 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)185186187class ParsingState(object):189188 def __init__(self, rargs):189 self.opts = {}190 self.largs = []191 self.rargs = rargs
32 unmodified lines
224 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 = []230233 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 lines
239 """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 lines
273 raise274 return state.opts, state.largs, state.order275276 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 )280281 for idx, arg in enumerate(self._args):282 arg.process(pargs[idx], state)283
5 unmodified lines
289 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 lines
321 # not a very interesting subset!322323 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)327328 option = self._long_opt[opt]329 if option.takes_value:
13 unmodified lines
343 value = tuple(state.rargs[:nargs])344 del state.rargs[:nargs]345346 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)348349 else:350 value = None351
43 unmodified lines
395 # 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))400401 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 lines
modified:src/click/termui.py+127 added-75 removed
25 unmodified lines
26# functions to customize how they work.27visible_prompt_func = raw_input2829_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"495051def hidden_prompt_func(prompt):52 import getpass5354 return getpass.getpass(prompt)555656def _build_prompt(text, suffix, show_default=False, default=None, show_choices=True, type=None):57def _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 + suffix666768def _format_default(default):
2 unmodified lines
7172 return default737472def 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):75def 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.8990 If the user aborts the input by sending a interrupt signal, this
34 unmodified lines
125 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/issue24711
3 unmodified lines
137138 if value_proc is None:139 value_proc = convert_type(type, default)140129 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 )144145 while 1:146 while 1:147 value = prompt_func(prompt)
7 unmodified lines
155 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)170171158def confirm(text, default=False, abort=False, prompt_suffix=': ',159 show_default=True, err=False):172def confirm(173 text, default=False, abort=False, prompt_suffix=": ", show_default=True, err=False174):175 """Prompts for confirmation (yes/no question).176177 If the user aborts the input by sending a interrupt signal this178 function will catch it and raise a :exc:`Abort` exception.
9 unmodified lines
188 :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 lines
221 """222 # If shutil has get_terminal_size() (Python 3.3 and later) use that223 if sys.version_info >= (3, 3):224 import shutil225209 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 lines
240 def ioctl_gwinsz(fd):241 try:242 import fcntl243 import termios227 cr = struct.unpack(228 'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))244245 cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))246 except Exception:247 return248 return cr249
7 unmodified lines
257 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])263264265def echo_via_pager(text_or_generator, color=None):
17 unmodified lines
283 else:284 i = iter(text_or_generator)285286 # 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)288289 from ._termui_impl import pager290291 return pager(itertools.chain(text_generator, "\n"), color)292293278def 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):294def 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 rendered
77 unmodified lines
391 codes are included anywhere in the progress bar output392 which is not the case by default.393 """394 from ._termui_impl import ProgressBar395396 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 )413414415def clear():416 """Clears the terminal screen. This will have the effect of clearing
7 unmodified lines
424 # 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")431432395def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,396 blink=None, reverse=None, reset=True):433def 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 lines
494 """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)520521522def unstyle(text):523 """Removes ANSI styling information from a string. Usually it's not
23 unmodified lines
547 message = style(message, **styles)548 return echo(message, file=file, nl=nl, err=err, color=color)549550504def edit(text=None, editor=None, env=None, require_save=True,505 extension='.txt', filename=None):551def 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 be
20 unmodified lines
578 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)582583 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 lines
610 might have weird effects if the URL does not point to611 the filesystem.612 """613 from ._termui_impl import open_url614615 return open_url(url, wait=wait, locate=locate)616617618# If this is provided, getchar() calls into this instead. This is used
28 unmodified lines
647648649def raw_terminal():650 from ._termui_impl import raw_terminal as f651652 return f()653654603def pause(info='Press any key to continue ...', err=False):655def 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 lines
modified:src/click/testing.py+44 added-36 removed
11 unmodified lines
12# 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.16clickpkg = sys.modules[__name__.rsplit('.', 1)[0]]16clickpkg = sys.modules[__name__.rsplit(".", 1)[0]]171819if PY2:20 from cStringIO import StringIO
2 unmodified lines
23 from ._compat import _find_binary_reader242526class EchoingStdin(object):2727 def __init__(self, input, output):28 self._input = input29 self._output = output30
21 unmodified lines
525354def 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.")6364 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 lines
7273class Result(object):74 """Holds the captured result of an invoked CLI script."""7577 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_bytes
13 unmodified lines
9697 @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 )103104 @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 )112111113 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 )118119120class CliRunner(object):
16 unmodified lines
137 noisy stderr, such that each may be measured138 independently139 """140140 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_stderr
2 unmodified lines
150 """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"155156 def make_env(self, overrides=None):157 """Returns the environment overrides for invoking a script."""158 rv = dict(self.env)
41 unmodified lines
200 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)208209 if self.mix_stderr:210 sys.stderr = sys.stdout211212 sys.stdin = input213214 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 val220221 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")225226 def _getchar(echo):227 char = sys.stdin.read(1)228 if echo:
46 unmodified lines
275 clickpkg.termui._getchar = old__getchar_func276 clickpkg.utils.should_strip_ansi = old_should_strip_ansi277 clickpkg.formatting.FORCED_WIDTH = old_forced_width278281 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 lines
341 exception = e342343 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 = 1347348 except Exception as e:349 if not catch_exceptions:
8 unmodified lines
358 stderr = None359 else:360 stderr = outstreams[1].getvalue()361362 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 )370371 @contextlib.contextmanager372 def isolated_filesystem(self):373 """A context manager that creates a temporary folder and changes
13 unmodified lines
modified:src/click/types.py+168 added-110 removed
25 unmodified lines
26 * 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 """3031 is_composite = False3233 #: the descriptive name of this type34 name = None
33 unmodified lines
68 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)7374 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 lines
84 raise NotImplementedError()858687class FuncParamType(ParamType):8788 def __init__(self, func):89 self.name = func.__name__90 self.func = func91
3 unmodified lines
95 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)101102103class UnprocessedParamType(ParamType):104 name = 'text'104 name = "text"105106 def convert(self, value, param, ctx):107 return value108109 def __repr__(self):110 return 'UNPROCESSED'110 return "UNPROCESSED"111112113class StringParamType(ParamType):114 name = 'text'114 name = "text"115116 def convert(self, value, param, ctx):117 if isinstance(value, bytes):118 enc = _get_argv_encoding()
4 unmodified lines
123 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 value132133 def __repr__(self):134 return 'STRING'134 return "STRING"135136137class Choice(ParamType):138 """The choice type allows a value to be checked against a fixed set
11 unmodified lines
150 :param case_sensitive: Set to false to make choices case151 insensitive. Defaults to true.152 """153154 name = 'choice'154 name = "choice"155156 def __init__(self, choices, case_sensitive=True):157 self.choices = choices158 self.case_sensitive = case_sensitive159160 def get_metavar(self, param):161 return '[%s]' % '|'.join(self.choices)161 return "[%s]" % "|".join(self.choices)162163 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)165166 def convert(self, value, param, ctx):167 # Match through normalization and case sensitivity168 # first do token_normalize_func, then lowercase
23 unmodified lines
192193 if normed_value in normed_choices:194 return normed_choices[normed_value]195196 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 )201202 def __repr__(self):200 return 'Choice(%r)' % list(self.choices)203 return "Choice(%r)" % list(self.choices)204205206class DateTime(ParamType):207 """The DateTime type converts date strings into `datetime` objects.
14 unmodified lines
222 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'226227 name = "datetime"228229 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"]231232 def get_metavar(self, param):233 return '[{}]'.format('|'.join(self.formats))233 return "[{}]".format("|".join(self.formats))234235 def _try_to_convert_date(self, value, format):236 try:237 return datetime.strptime(value, format)
7 unmodified lines
245 if dtime:246 return dtime247248 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 )253254 def __repr__(self):253 return 'DateTime'255 return "DateTime"256257258class IntParamType(ParamType):257 name = 'integer'259 name = "integer"260261 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)266267 def __repr__(self):266 return 'INT'268 return "INT"269270271class IntRange(IntParamType):272 """A parameter that works similar to :data:`click.INT` but restricts
2 unmodified lines
275 between the two edges.276277 See :ref:`ranges` for an example.278 """277 name = 'integer range'279280 name = "integer range"281282 def __init__(self, min=None, max=None, clamp=False):283 self.min = min284 self.max = max285 self.clamp = clamp
4 unmodified lines
290 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 rv321322 def __repr__(self):305 return 'IntRange(%r, %r)' % (self.min, self.max)323 return "IntRange(%r, %r)" % (self.min, self.max)324325326class FloatParamType(ParamType):309 name = 'float'327 name = "float"328329 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)334335 def __repr__(self):319 return 'FLOAT'336 return "FLOAT"337338339class FloatRange(FloatParamType):340 """A parameter that works similar to :data:`click.FLOAT` but restricts
2 unmodified lines
343 between the two edges.344345 See :ref:`ranges` for an example.346 """330 name = 'float range'347348 name = "float range"349350 def __init__(self, min=None, max=None, clamp=False):351 self.min = min352 self.max = max353 self.clamp = clamp
4 unmodified lines
358 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 rv389390 def __repr__(self):358 return 'FloatRange(%r, %r)' % (self.min, self.max)391 return "FloatRange(%r, %r)" % (self.min, self.max)392393394class BoolParamType(ParamType):362 name = 'boolean'395 name = "boolean"396397 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)406407 def __repr__(self):375 return 'BOOL'408 return "BOOL"409410411class UUIDParameterType(ParamType):379 name = 'uuid'412 name = "uuid"413414 def convert(self, value, param, ctx):415 import uuid416417 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)423424 def __repr__(self):391 return 'UUID'425 return "UUID"426427428class File(ParamType):429 """Declares a parameter to be a file for reading or writing. The file
20 unmodified lines
450 is useful if a file regularly read by other users is modified.451452 See :ref:`file-args` for more information.453 """420 name = 'filename'454455 name = "filename"456 envvar_list_splitter = os.path.pathsep457423 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 = lazy
1 unmodified line
466467 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 False475476 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 value480481 lazy = self.resolve_lazy_flag(value)482483 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 f490454 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 the
4 unmodified lines
502 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 )512513514class Path(ParamType):515 """The path type is similar to the :class:`File` type but it performs
24 unmodified lines
540 means the return value will be either bytes or541 unicode depending on what makes most sense given the542 input data Click deals with.543 """544545 envvar_list_splitter = os.path.pathsep546507 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 = writable
2 unmodified lines
564 self.allow_dash = allow_dash565 self.type = path_type566567 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"576577 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 lines
584585 def convert(self, value, param, ctx):586 rv = value587540 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"-", "-")589590 if not is_dash:591 if self.resolve_path:592 rv = os.path.realpath(rv)
2 unmodified lines
595 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 )604605 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 )631632 return self.coerce_path_result(rv)633634
23 unmodified lines
658 return len(self.types)659660 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))667668669def convert_type(ty, default=None):
30 unmodified lines
700 # 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 lines
modified:src/click/utils.py+40 added-36 removed
28 unmodified lines
29echo_native_types = string_types + (bytes, bytearray)303132def _posixify(name):33 return '-'.join(name.split()).lower()33 return "-".join(name.split()).lower()343536def safecall(func):37 """Wraps a function so that it swallows exceptions."""3839 def wrapper(*args, **kwargs):40 try:41 return func(*args, **kwargs)42 except Exception:43 pass4445 return wrapper464748def make_str(value):
1 unmodified line
50 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)565758def make_default_short_help(help, max_length=45):
3 unmodified lines
62 result = []63 done = False6465 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_length7978 return ''.join(result)80 return "".join(result)818283class LazyFile(object):84 """A lazy file works like a regular file but it does not fully open
1 unmodified line
86 filename parameter does make sense. This is useful for safely opening87 files for writing.88 """8988 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 = atomic9896 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 lines
112113 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)117118 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 error
1 unmodified line
122 """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 FileError131132 raise FileError(self.name, hint=get_streerror(e))133 self._f = rv134 return rv135
20 unmodified lines
156 return iter(self._f)157158159class KeepOpenFile(object):158160 def __init__(self, file):161 self._file = file162163 def __getattr__(self, name):
69 unmodified lines
233 if message is not None and not isinstance(message, echo_native_types):234 message = text_type(message)235236 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"242243 # 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 stream
38 unmodified lines
284 ``'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()290291291def get_text_stream(name, encoding=None, errors='strict'):292def 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 lines
301 :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)307308308def open_file(filename, mode='r', encoding=None, errors='strict',309 lazy=False, atomic=False):309def 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 lines
332 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 lines
412 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 )431432433class PacifyFlushWrapper(object):434 """This wrapper is used to catch and suppress BrokenPipeErrors resulting
11 unmodified lines
446 try:447 self.wrapped.flush()448 except IOError as e:449 import errno450451 if e.errno != errno.EPIPE:452 raise453454 def __getattr__(self, attr):
1 unmodified line
modified:tests/conftest.py+1 added-1 removed
1 unmodified line
23from click.testing import CliRunner456@pytest.fixture(scope='function')6@pytest.fixture(scope="function")7def runner(request):8 return CliRunner()
modified:tests/test_arguments.py+115 added-106 removed
8 unmodified lines
91011def 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)1819 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 ]252627def test_nargs_default(runner):28 try:2930 @click.command()30 @click.argument('src', nargs=-1, default=42)31 @click.argument("src", nargs=-1, default=42)32 def copy(src):33 pass3435 except TypeError as e:34 assert 'nargs=-1' in str(e)36 assert "nargs=-1" in str(e)37 else:38 assert False394041def 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)4847 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 ]555657def test_nargs_tup_composite(runner):
4 unmodified lines
62 dict(nargs=2, type=(str, int)),63 ]6465 for opts in variations:6667 @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)7169 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 ]777879def test_nargs_err(runner):80 @click.command()78 @click.argument('x')81 @click.argument("x")82 def copy(x):83 click.echo(x)8482 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"8886 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.output929394def 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"101102 # 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")111107 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 )117118119def 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)129130 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!"136129 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 == 0140141142def 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)147140 result = runner.invoke(foo, ['-'])141 assert result.output == '-\n'148 result = runner.invoke(foo, ["-"])149 assert result.output == "-\n"150 assert result.exit_code == 0151152153def 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"162163 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"171172173def 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()179180 result = runner.invoke(inout, [])181 assert not result.exception175 assert result.output == 'Foo bar baz\n'182 assert result.output == "Foo bar baz\n"183184185def 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))190184 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"196197 @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))201194 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"205206207def 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))212213 result = runner.invoke(cmd, [])214 assert result.exit_code == 0207 assert result.output == 'arg:\n'215 assert result.output == "arg:\n"216217 @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))221222 result = runner.invoke(cmd2, [])223 assert result.exit_code == 2224 assert 'Missing argument "ARG..."' in result.output225226227def 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)232233 result = runner.invoke(cmd, [])234 assert result.exit_code == 2235 assert 'Missing argument "ARG".' in result.output
9 unmodified lines
245246247def 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)252253 result = runner.invoke(cli, [])254 assert result.exit_code == 0247 assert result.output == 'test\n'255 assert result.output == "test\n"256257258def 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)266259 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 ]273266 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 ]280281282def 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)290283 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 ]297298299def 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)307300 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 ]314315316def 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)322323 result = runner.invoke(cmd, [])316 assert result.output.strip() == '3'324 assert result.output.strip() == "3"325318 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"328321 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.output332333334def test_multiple_param_decls_not_allowed(runner):335 with pytest.raises(TypeError):336337 @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 lines
5from click._bashcomplete import get_choices678def 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]111213def choices_with_help(cli, args, incomplete):14 return list(get_choices(cli, 'dummy', args, incomplete))14 return list(get_choices(cli, "dummy", args, incomplete))151617def test_single_command():18 @click.command()19 @click.option('--local-opt')19 @click.option("--local-opt")20 def cli(local_opt):21 pass2223 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, [], "") == []252627def 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 pass3233 assert choices_without_help(cli, [], '-') == ['--shout', '--no-shout']33 assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout"]343536def 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 pass4142 @cli.command()43 @click.option('--local-opt')43 @click.option("--local-opt")44 def sub(local_opt):45 pass4647 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"]515253def 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 pass5859 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"], "") == []616263def test_small_chain():64 @click.group()65 @click.option('--global-opt')65 @click.option("--global-opt")66 def cli(global_opt):67 pass6869 @cli.command()70 @click.option('--local-opt')70 @click.option("--local-opt")71 def sub(local_opt):72 pass7374 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"]787980def 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 pass8586 @cli.group('asub')87 @click.option('--asub-opt')86 @cli.group("asub")87 @click.option("--asub-opt")88 def asub(asub_opt):89 pass9091 @asub.group('bsub')92 @click.option('--bsub-opt')91 @asub.group("bsub")92 @click.option("--bsub-opt")93 def bsub(bsub_opt):94 pass9596 COLORS = ['red', 'green', 'blue']96 COLORS = ["red", "green", "blue"]9798 def get_colors(ctx, args, incomplete):99 for c in COLORS:100 if c.startswith(incomplete):101 yield c
2 unmodified lines
104 for c in COLORS:105 if incomplete in c:106 yield c107107 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"]110111 @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 pass118117 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"]150151152def 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 pass158159 @cli.command()141 @click.option('--asub-opt')160 @click.option("--asub-opt")161 def asub(asub_opt):162 pass163145 @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 pass169170 @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 pass175157 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")]196197198def 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 pass205179 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"]211212213def 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 pass220194 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"]241210 assert choices_without_help(cli, ['--opt1', 'invalid_opt'], '-') == ['--opt2', '--opt3']242 assert choices_without_help(cli, ["--opt1", "invalid_opt"], "-") == [243 "--opt2",244 "--opt3",245 ]246247248def 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 pass255221 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"]262263264def 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 pass270236 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"]273274275def 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 pass281247 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"], "") == []286287288def 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 pass294260 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"]298299300def 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 pass306272 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"]311312313def test_variadic_argument_complete():279314 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"]316317 @click.group()318 def entrypoint():319 pass320321 @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 pass326327 entrypoint.add_command(subcommand)328295 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 )339340341def test_long_chain_choice():342 @click.group()343 def cli():344 pass345346 @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 pass353311 @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 pass364318 @sub.group('csub')365 @sub.group("csub")366 def csub():367 pass368369 @csub.command()370 def dsub():371 pass372326 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"]409410411def test_chained_multi():412 @click.group()
19 unmodified lines
432 @csub.command()433 def esub():434 pass435371 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"]440441442def 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 pass448449 @cli.group(hidden=True)
8 unmodified lines
458 def asub():459 pass460461 @cli.command(hidden=True)397 @click.option('--hname')462 @click.option("--hname")463 def hsub():464 pass465401 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"]476477478@pytest.mark.parametrize(479 ("args", "part", "expect"),
21 unmodified lines
modified:tests/test_basic.py+217 added-207 removed
7 unmodified lines
8def test_basic_functionality(runner):9 @click.command()10 def cli():11 """Hello World!"""12 click.echo('I EXECUTED')12 click.echo("I EXECUTED")1314 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.output2021 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 == 0252627def test_repr():
8 unmodified lines
36 @group.command()37 def subcommand():38 pass3940 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>"434445def test_return_values():46 @click.command()47 def cli():48 return 424950 with cli.make_context('foo', []) as ctx:50 with cli.make_context("foo", []) as ctx:51 rv = cli.invoke(ctx)52 assert rv is 42535455def 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")6061 @cli.command()62 def subcommand():63 """This is a subcommand."""64 click.echo('SUBCOMMAND EXECUTED')64 click.echo("SUBCOMMAND EXECUTED")6566 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.output7374 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.output798081def 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)8687 result = runner.invoke(cli, [])88 assert not result.exception89 assert 'FOO:[no value]' in result.output89 assert "FOO:[no value]" in result.output9091 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.output9495 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.output9899 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.output102103 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.output106107108def 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))113114 result = runner.invoke(cli, [])115 assert not result.exception116 assert 'FOO:[84]' in result.output116 assert "FOO:[84]" in result.output117118 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.output121122 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.output125126127def 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)135136 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.output139140 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.output143144 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.output147148149def 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)155156 result = runner.invoke(cli, [])157 assert not result.exception159 assert 'FOO:[42.0]' in result.output158 assert "FOO:[42.0]" in result.output159161 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.output163165 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.output167168169def test_boolean_option(runner):170 for default in True, False:171172 @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)176178 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" % default186187 for default in True, False:188189 @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)193194 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)200201202def test_boolean_conversion(runner):203 for default in True, False:204205 @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)209209 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"214214 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"219220 result = runner.invoke(cli, [])221 assert not result.exception221 assert result.output == '%s\n' % default222 assert result.output == "%s\n" % default223224225def 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")230231 @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())235236 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"])239240 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"244245246def test_file_lazy_mode(runner):247 do_io = False248249 @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")254255 @click.command()255 @click.option('--file', type=click.File('r'))256 @click.option("--file", type=click.File("r"))257 def output(file):258 pass259260 with runner.isolated_filesystem():260 os.mkdir('example.txt')261 os.mkdir("example.txt")262263 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 == 1266267 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 == 0270270 result_out = runner.invoke(output, ['--file=example.txt'])271 result_out = runner.invoke(output, ["--file=example.txt"])272 assert result_out.exception273274 @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")278279 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 )287288289def 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")295296 with runner.isolated_filesystem():295 os.mkdir('test')297 os.mkdir("test")298297 result = runner.invoke(write_to_dir, ['-O', 'test'])299 result = runner.invoke(write_to_dir, ["-O", "test"])300 assert not result.exception301300 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"304303 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 )310311 @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))316317 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 )322318 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.output326327 @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))331332 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.output335331 result = runner.invoke(exists, ['-f', '.'])332 assert 'exists=True' in result.output336 result = runner.invoke(exists, ["-f", "."])337 assert "exists=True" in result.output338339340def 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)345341 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"349345 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 )356350 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.output359360361def test_datetime_option_default(runner):355362 @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"))366361 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"370365 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"374369 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.output382376 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 )387388389def 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"))394387 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"398399400def 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)405398 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"409402 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 )416417 @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)421412 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"425416 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"429420 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"433434435def 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)440431 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"444435 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 )451452 @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)456445 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"460449 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"464453 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"468469470def 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)475476 result = runner.invoke(cli, [])
8 unmodified lines
485 called.append(value)486 return value487488 @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 pass498494 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 ]522523524def 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)529520 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.output533534535def test_hidden_command(runner):536 @click.group()
3 unmodified lines
540 @cli.command(hidden=True)541 def nope():542 pass543534 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.output547548549def test_hidden_group(runner):550 @click.group()
7 unmodified lines
558 @subgroup.command()559 def nope():560 pass561552 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.output
modified:tests/test_chain.py+78 added-75 removed
4 unmodified lines
5import click678def 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 )131415def test_basic_chaining(runner):16 @click.group(chain=True)17 def cli():18 pass1920 @cli.command('sdist')20 @cli.command("sdist")21 def sdist():22 click.echo('sdist called')22 click.echo("sdist called")2324 @cli.command('bdist')24 @cli.command("bdist")25 def bdist():26 click.echo('bdist called')26 click.echo("bdist called")2728 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 ]353637def test_chaining_help(runner):
1 unmodified line
39 def cli():40 """ROOT HELP"""41 pass4243 @cli.command('sdist')43 @cli.command("sdist")44 def sdist():45 """SDIST HELP"""46 click.echo('sdist called')46 click.echo("sdist called")4748 @cli.command('bdist')48 @cli.command("bdist")49 def bdist():50 """BDIST HELP"""51 click.echo('bdist called')51 click.echo("bdist called")5253 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.output5758 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.output6162 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.output6566 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.output697071def test_chaining_with_options(runner):72 @click.group(chain=True)73 def cli():74 pass7576 @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)8081 @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)8586 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 ]929394def test_chaining_with_arguments(runner):95 @click.group(chain=True)96 def cli():97 pass9899 @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)103104 @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)108109 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 ]115116117def 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 pass122123 @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)130131 @cli.command('uppercase')131 @cli.command("uppercase")132 def make_uppercase():133 def processor(iterator):134 for line in iterator:135 yield line.upper()136137 return processor138138 @cli.command('strip')139 @cli.command("strip")140 def make_strip():141 def processor(iterator):142 for line in iterator:143 yield line.strip()144145 return processor146145 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 ]153152 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 ]160159 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 ]167168169def test_args_and_chain(runner):
12 unmodified lines
182 @cli.command()183 def c():184 debug()185185 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 ]194195196def test_multicommand_arg_behavior(runner):197 with pytest.raises(RuntimeError):198199 @click.group(chain=True)198 @click.argument('forbidden', required=False)200 @click.argument("forbidden", required=False)201 def bad_cli():202 pass203204 with pytest.raises(RuntimeError):205206 @click.group(chain=True)204 @click.argument('forbidden', nargs=-1)207 @click.argument("forbidden", nargs=-1)208 def bad_cli2():209 pass210211 @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)215216 @cli.command()217 def a():215 click.echo('a')218 click.echo("a")219217 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 ]226227228@pytest.mark.xfail
17 unmodified lines
246 @cli.command()247 def l1b():248 debug()249247 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 lines
10 def cli(ctx):11 return ctx.invoke(other_cmd, arg=42)1213 @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)1718 result = runner.invoke(cli, [])19 assert not result.exception20 assert result.output == '42\n'20 assert result.output == "42\n"212223def test_other_command_forward(runner):24 cli = click.Group()2526 @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)3031 @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)3738 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"414243def test_auto_shorthelp(runner):44 @click.group()
12 unmodified lines
57 def long():58 """This is a long text that is too long to show as short help59 and will be truncated instead."""6061 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 )727374def test_no_args_is_help(runner):75 @click.command(no_args_is_help=True)
1 unmodified line
77 pass7879 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.output828384def test_default_maps(runner):85 @click.group()86 def cli():87 pass8889 @cli.command()86 @click.option('--name', default='normal')90 @click.option("--name", default="normal")91 def foo(name):92 click.echo(name)9390 result = runner.invoke(cli, ['foo'], default_map={91 'foo': {'name': 'changed'}92 })94 result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})9596 assert not result.exception95 assert result.output == 'changed\n'97 assert result.output == "changed\n"9899100def 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)105106 @cli.command()107 def move():106 click.echo('move')108 click.echo("move")109110 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.output113112 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.output117116 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.output121120 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"125126127def test_base_command(runner):128 import optparse
2 unmodified lines
131 def cli():132 pass133134 class OptParseCommand(click.BaseCommand):133135 def __init__(self, name, parser, callback):136 click.BaseCommand.__init__(self, name)137 self.parser = parser138 self.callback = callback
14 unmodified lines
153154 def invoke(self, ctx):155 ctx.invoke(self.callback, ctx.args, **ctx.params)156156 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 )169170 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))174169 result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',170 'whatever.txt', 'whateverelse.txt'])175 cli.add_command(OptParseCommand("test", parser, test_callback))176177 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 ]186178 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 ]197198199def test_object_propagation(runner):200 for chain in False, True:201202 @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"] = debug209210 @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"))214205 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"218219220def test_other_command_invoke_with_defaults(runner):221 @click.command()
1 unmodified line
223 def cli(ctx):224 return ctx.invoke(other_cmd)225226 @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)232233 result = runner.invoke(cli, [])234 assert not result.exception225 assert result.output == '42\n'235 assert result.output == "42\n"236237238def 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")247248 @cli.command()249 def sync():240 click.echo('in subcommand')250 click.echo("in subcommand")251242 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"255256 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"259260261def 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))268261 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 ]275276277def test_deprecated_in_help_messages(runner):
1 unmodified line
279 def cmd_with_help():280 """CLI HELP"""281 pass282275 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.output285286 @click.command(deprecated=True)287 def cmd_without_help():288 pass289282 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.output292293294def test_deprecated_in_invocation(runner):295 @click.command(deprecated=True)296 def deprecated_cmd():297 debug()298299 result = runner.invoke(deprecated_cmd)292 assert 'DeprecationWarning:' in result.output300 assert "DeprecationWarning:" in result.output
modified:tests/test_compat.py+13 added-11 removed
8 unmodified lines
9 def legacy_callback(ctx, value):10 return value.upper()1112 @click.command()13 @click.option('--foo', callback=legacy_callback)13 @click.option("--foo", callback=legacy_callback)14 def cli(foo):15 click.echo(foo)1617 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.output212223def 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 script2526 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 script293031def 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 script3334 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 script383940@pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")41def test_is_jupyter_kernel_output():42 class JupyterKernelFakeStream(object):43 pass
4 unmodified lines
modified:tests/test_context.py+39 added-34 removed
3 unmodified lines
45def test_ensure_context_objects(runner):6 class Foo(object):7 def __init__(self):8 self.title = 'default'8 self.title = "default"910 pass_foo = click.make_pass_decorator(Foo, ensure=True)1112 @click.group()
5 unmodified lines
18 @pass_foo19 def test(foo):20 click.echo(foo.title)2122 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"252627def test_get_context_objects(runner):28 class Foo(object):29 def __init__(self):30 self.title = 'default'30 self.title = "default"3132 pass_foo = click.make_pass_decorator(Foo, ensure=True)3334 @click.group()35 @click.pass_context36 def cli(ctx):37 ctx.obj = Foo()38 ctx.obj.title = 'test'38 ctx.obj.title = "test"3940 @cli.command()41 @pass_foo42 def test(foo):43 click.echo(foo.title)4445 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"484950def test_get_context_objects_no_ensuring(runner):51 class Foo(object):52 def __init__(self):53 self.title = 'default'53 self.title = "default"5455 pass_foo = click.make_pass_decorator(Foo)5657 @click.group()58 @click.pass_context59 def cli(ctx):60 ctx.obj = Foo()61 ctx.obj.title = 'test'61 ctx.obj.title = "test"6263 @cli.command()64 @pass_foo65 def test(foo):66 click.echo(foo.title)6768 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"717273def test_get_context_objects_missing(runner):74 class Foo(object):
10 unmodified lines
85 @pass_foo86 def test(foo):87 click.echo(foo.title)8889 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 )969798def test_multi_enter(runner):99 called = []
2 unmodified lines
102 @click.pass_context103 def cli(ctx):104 def callback():105 called.append(True)106107 ctx.call_on_close(callback)108109 with ctx:110 pass
8 unmodified lines
119 @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"125126 assert click.get_current_context(silent=True) is None127 runner.invoke(cli, [], catch_exceptions=False)128 assert click.get_current_context(silent=True) is None129130131def test_context_meta(runner):129 LANG_KEY = __name__ + '.lang'132 LANG_KEY = __name__ + ".lang"133134 def set_language(value):135 click.get_current_context().meta[LANG_KEY] = value136137 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")139140 @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"146147 runner.invoke(cli, [], catch_exceptions=False)148149
26 unmodified lines
176def test_pass_obj(runner):177 @click.group()178 @click.pass_context179 def cli(ctx):177 ctx.obj = 'test'180 ctx.obj = "test"181182 @cli.command()183 @click.pass_obj184 def test(obj):185 click.echo(obj)186184 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"190191192def test_close_before_pop(runner):193 called = []194195 @click.command()196 @click.pass_context197 def cli(ctx):195 ctx.obj = 'test'198 ctx.obj = "test"199200 @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!')204205 click.echo("aha!")206207 result = runner.invoke(cli, [])208 assert not result.exception205 assert result.output == 'aha!\n'209 assert result.output == "aha!\n"210 assert called == [True]211212213def test_make_pass_decorator_args(runner):214 """215 Test to check that make_pass_decorator doesn't consume arguments based on216 invocation order.217 """218219 class Foo(object):215 title = 'foocmd'220 title = "foocmd"221222 pass_foo = click.make_pass_decorator(Foo)223224 @click.group()
12 unmodified lines
237 @click.pass_context238 def test2(ctx, foo):239 click.echo(foo.title)240236 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"244240 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"248249250def test_exit_not_standalone():251 @click.command()252 @click.pass_context253 def cli(ctx):254 ctx.exit(1)255251 assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 1256 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 1257258 @click.command()259 @click.pass_context260 def cli(ctx):261 ctx.exit(0)262258 assert cli.main([], 'test_exit_not_standalone', standalone_mode=False) == 0263 assert cli.main([], "test_exit_not_standalone", standalone_mode=False) == 0
modified:tests/test_defaults.py+12 added-12 removed
1 unmodified line
234def 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)1011 result = runner.invoke(cli, [])12 assert not result.exception13 assert 'FOO:[42.0]' in result.output13 assert "FOO:[42.0]" in result.output141516def 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)2324 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 ]303132def 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)4041 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 lines
24 And this is a paragraph25 that will be rewrapped again.26 """2728 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 ]515253def test_wrapping_long_options_strings(runner):
7 unmodified lines
61 """Second level62 """6364 @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 """7475 # 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 ]899091def test_wrapping_long_command_name(runner):
7 unmodified lines
99 """Second level100 """101102 @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 """112114 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 ]127128129def test_formatting_empty_help_lines(runner):
2 unmodified lines
132 """Top level command133134 """135136 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 ]148149150def 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)155156 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 ]164165166def test_formatting_usage_error_metavar_missing_arg(runner):167 """168 :author: @r-m-n169 Including attribution to #612170 """171172 @click.command()172 @click.argument('arg', metavar='metavar')173 @click.argument("arg", metavar="metavar")174 def cmd(arg):175 pass176177 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 ]185186187def 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 pass192192 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 ]201202203def test_formatting_usage_error_nested(runner):
1 unmodified line
205 def cmd():206 pass207208 @cmd.command()208 @click.argument('bar')209 @click.argument("bar")210 def foo(bar):210 click.echo('foo:' + bar)211 click.echo("foo:" + bar)212212 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 ]221222223def 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)228229 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 ]236237238def 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)243244 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 ]252253254def test_formatting_custom_type_metavar(runner):255 class MyType(click.ParamType):256 def get_metavar(self, param):257 return "MY_TYPE"
3 unmodified lines
261 @click.argument("param", type=MyType())262 def cmd(param):263 pass264263 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 ]273274275def test_truncating_docstring(runner):
9 unmodified lines
285286 :param click.core.Context ctx: Click context.287 """288287 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 ]302303304def test_global_show_default(runner):
1 unmodified line
306 @click.option("-f", "in_file", default="out.txt", help="Output file name")307 def cli():308 pass309308 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 ]318319320def 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 pass325324 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 ]337338339def 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 pass344343 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 lines
45from click._compat import WIN678IMPORT_TEST = b'''\8IMPORT_TEST = b"""\9try:10 import __builtin__ as builtins11except ImportError:12 import builtins
13 unmodified lines
26import click27rv = list(found_imports)28import json29click.echo(json.dumps(rv))30'''30"""3132ALLOWED_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])32ALLOWED_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)5657if WIN:39 ALLOWED_IMPORTS.update(['ctypes', 'ctypes.wintypes', 'msvcrt', 'time',40 'zlib'])58 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])596061def 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]6667 if sys.version_info[0] != 2:49 rv = rv.decode('utf-8')68 rv = rv.decode("utf-8")69 imported = json.loads(rv)7071 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_IMPORTS
modified:tests/test_normalization.py+10 added-10 removed
4 unmodified lines
567def 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)1415 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"171819def 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)2425 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"272829def test_command_normalization(runner):30 @click.group(context_settings=CONTEXT_SETTINGS)
1 unmodified line
32 pass3334 @cli.command()35 def foo():36 click.echo('here!')36 click.echo("here!")3738 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 lines
91011def 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))1718 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"2122 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 None252627def test_invalid_option(runner):28 try:2930 @click.command()30 @click.option('foo')31 @click.option("foo")32 def cli(foo):33 pass3435 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."394041def test_invalid_nargs(runner):42 try:4344 @click.command()43 @click.option('--foo', nargs=-1)45 @click.option("--foo", nargs=-1)46 def cli(foo):47 pass4849 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."535455def 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)6159 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 ]686970def 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)7574 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"7978 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 )8687 result = runner.invoke(cli, [])88 assert not result.exception85 assert result.output == 'verbosity=0\n'89 assert result.output == "verbosity=0\n"9087 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 None939491@pytest.mark.parametrize('unknown_flag', ['--foo', '-f'])95@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])96def test_unknown_options(runner, unknown_flag):97 @click.command()98 def cli():99 pass100101 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.output104105106def 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))111108 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"115116 result = runner.invoke(cli, [])117 assert result.exception118 assert 'Error: Missing option "-m" / "--message".' in result.output119120121def 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)126123 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"130131132def 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))137134 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"143144 @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))148144 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"152153 @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))157153 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"166167168def 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 pass174168 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.output179180181def 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)188189 assert all(isinstance(e[0], int) for e in arg2)190 assert all(isinstance(e[1], text_type) for e in arg2)191185 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.exception196197198def 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)208197 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.output214215216def 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)226211 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.output232233234def test_toupper_envvar_prefix(runner):235 @click.command()220 @click.option('--arg')236 @click.option("--arg")237 def cmd(arg):238 click.echo(arg)239224 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"243244245def 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))250236 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"256257 @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))262247 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"268269270def 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 pass275260 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.output279280281def 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 pass286271 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.output290291292def test_show_envvar_auto_prefix_dash_in_command(runner):293 @click.group()294 def cli():295 pass296297 @cli.command()283 @click.option('--baz', show_envvar=True)298 @click.option("--baz", show_envvar=True)299 def foo_bar(baz):300 pass301287 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.output305306307def 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 value312313 @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)317304 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.output320308 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"323324325def 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)330318 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.output340341342def test_legacy_options(runner):343 @click.command()331 @click.option('-whatever')344 @click.option("-whatever")345 def cmd(whatever):346 click.echo(whatever)347335 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"352353354def test_missing_option_string_cast():355 ctx = click.Context(click.Command(""))356357 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)359360 assert str(excinfo.value) == "missing parameter: a"361362363def 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)368369 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 choices376377378def 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)383373 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"387377 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"391381 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"395396 @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)400390 result = runner.invoke(cmd2, ['--foo', 'apple'])401 result = runner.invoke(cmd2, ["--foo", "apple"])402 assert result.exit_code == 2403393 result = runner.invoke(cmd2, ['--foo', 'oRANGe'])404 result = runner.invoke(cmd2, ["--foo", "oRANGe"])405 assert result.exit_code == 2406396 result = runner.invoke(cmd2, ['--foo', 'Apple'])407 result = runner.invoke(cmd2, ["--foo", "Apple"])408 assert result.exit_code == 0409410411def 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)416407 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"420421422def test_option_help_preserve_paragraphs(runner):423 @click.command()
9 unmodified lines
433 )434 def cmd(config):435 pass436427 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 line
443 "{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.output446447448def 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"453454 @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)458459 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.output462463464def 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")469470 @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)474464 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.output478479480def test_option_custom_class_reusable(runner):481 """Ensure we can reuse a custom class option. See Issue #926"""482483 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")487488 # 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")490491 @click.command()492 @testoption493 def cmd1(testoption):
6 unmodified lines
500501 # Both of the commands should have the --help option now.502 for cmd in (cmd1, cmd2):503493 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.output507508509def 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 pass514515 result = runner.invoke(cmd)
1 unmodified line
517518519def 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)524514 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"531532 @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)536526 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"543533@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])545def test_option_names(runner, option_args, expected):544545@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)560def 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]))565566 assert cmd.params[0].name == expected567568 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 lines
272829def test_progressbar_strip_regression(runner, monkeypatch):30 fake_clock = FakeClock()31 label = ' padded line'31 label = " padded line"3233 @click.command()34 def cli():35 with _create_progress(label=label) as progress:36 for thing in progress:37 fake_clock.advance_time()3839 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, []).output424344def test_progressbar_length_hint(runner, monkeypatch):
18 unmodified lines
63 fake_clock = FakeClock()6465 @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()7071 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 None757677def test_progressbar_hidden(runner, monkeypatch):78 fake_clock = FakeClock()79 label = 'whatever'79 label = "whatever"8081 @click.command()82 def cli():83 with _create_progress(label=label) as progress:84 for thing in progress:85 fake_clock.advance_time()8687 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 == ""909192@pytest.mark.parametrize('avg, expected', [([], 0.0), ([1, 4], 2.5)])92@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])93def test_progressbar_time_per_iteration(runner, avg, expected):94 with _create_progress(2, avg=avg) as progress:95 assert progress.time_per_iteration == expected969798@pytest.mark.parametrize('finished, expected', [(False, 5), (True, 0)])98@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])99def test_progressbar_eta(runner, finished, expected):100 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:101 assert progress.eta == expected102103104@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)116def 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() == expected119120112@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)])122def 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)129130122@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)140def 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() == expected145146138@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 ])145def 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)157def 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() == expected169170155@pytest.mark.parametrize('test_item', ['test', None])171@pytest.mark.parametrize("test_item", ["test", None])172def test_progressbar_format_progress_line_with_show_func(runner, test_item):157173 def item_show_func(item):174 return item175161 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 lines
185def 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"192193194def 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."202203204def test_progressbar_is_iterator(runner, monkeypatch):205 fake_clock = FakeClock()206207 @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 break216200 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)219220 result = runner.invoke(cli, [])221 assert result.exception is None222223224def 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 pass231232 @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 pass241220 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.output244223 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.output247248249@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)252def 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 lines
262def 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""267268269def test_progressbar_yields_all_items(runner):270 with click.progressbar(range(3)) as progress:
9 unmodified lines
280 for _ in progress:281 fake_clock.advance_time()282 print("")283267 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, []).output287271 lines = [line for line in output.split('\n') if '[' in line]288 lines = [line for line in output.split("\n") if "[" in line]289273 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]294295279@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.")299def 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_char304305291@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)312def 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_char319320300@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.")323def 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 lines
1718def 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()2930 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"3435 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"394041def 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()5253 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"5758 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"626364def 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)6970 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"7475 @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)7980 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"848586def test_getchar():87 @click.command()88 def continue_it():89 click.echo(click.getchar())9091 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"959697def test_catch_exceptions():98 class CustomError(Exception):
18 unmodified lines
117 result = runner.invoke(cli)118 assert result.exit_code == 1119120121@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.")122def test_with_color():123 @click.command()124 def cli():125 click.secho('hello world', fg='blue')125 click.secho("hello world", fg="blue")126127 runner = CliRunner()128129 result = runner.invoke(cli)130 assert result.output == 'hello world\n'130 assert result.output == "hello world\n"131 assert not result.exception132133 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.exception136137138def test_with_color_but_pause_not_blocking():
3 unmodified lines
142143 runner = CliRunner()144 result = runner.invoke(cli, color=True)145 assert not result.exception146 assert result.output == ''146 assert result.output == ""147148149def 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")155156 @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")161162 @click.command()163 def cli_int():164 click.echo('hello world')164 click.echo("hello world")165 sys.exit(1)166167 @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)172173 @click.command()174 def cli_float():175 click.echo('hello world')175 click.echo("hello world")176 sys.exit(1.0)177178 @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)183184 @click.command()185 def cli_no_error():186 click.echo('hello world')186 click.echo("hello world")187188 runner = CliRunner()189190 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"193194 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"197198 result = runner.invoke(cli_int)199 assert result.exit_code == 1200 assert result.output == 'hello world\n'200 assert result.output == "hello world\n"201202 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"205206 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"209210 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"213214 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"217218219def 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"])223224 runner = CliRunner()225226 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"233234 assert os.environ == env_orig235236
6 unmodified lines
243 runner = CliRunner(mix_stderr=False)244245 result = runner.invoke(cli_stderr)246247 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"250251 runner_mix = CliRunner(mix_stderr=True)252 result_mix = runner_mix.invoke(cli_stderr)253254 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"256257 with pytest.raises(ValueError):258 result_mix.stderr259
4 unmodified lines
264 runner = CliRunner(mix_stderr=False)265266 result = runner.invoke(cli_empty_stderr)267268 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 == ""271272273@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)283def test_args(args, expected_output):281284 @click.command()283 @click.option('--foo', default='bar')285 @click.option("--foo", default="bar")286 def cli_args(foo):287 click.echo(foo)288289 runner = CliRunner()
9 unmodified lines
299300 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 lines
111213def 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"2223 # 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 StringIO2728 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"3435 # 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")3940 result = runner.invoke(cli, [])39 assert result.stdout_bytes == b'\xf6\n'41 assert result.stdout_bytes == b"\xf6\n"4243 # 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"474849def test_echo_custom_file():50 import io5152 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"555657@pytest.mark.parametrize(58 ("styles", "ref"),
24 unmodified lines
83 assert click.style("x y", **styles) == ref84 assert click.unstyle(ref) == "x y"858684@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"),])88def test_unstyle_other_ansi(text, expect):89 assert click.unstyle(text) == expect90919492def 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"9798 # 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 )103104105def 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 :(")112115 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"116119 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"120123 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"124125 @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 :(")131134 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"135138 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"139142 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"143144147@pytest.mark.skipif(WIN, reason='Different behavior on windows.')145@pytest.mark.skipif(WIN, reason="Different behavior on windows.")146def test_prompts_abort(monkeypatch, capsys):147 def f(_):148 raise KeyboardInterrupt()149152 monkeypatch.setattr('click.termui.hidden_prompt_func', f)150 monkeypatch.setattr("click.termui.hidden_prompt_func", f)151152 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.")156157 out, err = capsys.readouterr()160 assert out == 'Password: \nScrew you.\n'158 assert out == "Password: \nScrew you.\n"159160161def _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"166167170@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)183def 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)186187 expected_output = test[0]188 test_input = test[1]()189
2 unmodified lines
192 out, err = capfd.readouterr()193 assert out == expected_output194195195@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.")197def 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)200200 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"204205 click.echo(styled_text, color=False)206 out, err = capfd.readouterr()206 assert out == text + '\n'207 assert out == text + "\n"208209 click.echo(styled_text, color=True)210 out, err = capfd.readouterr()210 assert out == styled_text + '\n'211 assert out == styled_text + "\n"212213 isatty = True214 click.echo(styled_text)215 out, err = capfd.readouterr()215 assert out == styled_text + '\n'216 assert out == styled_text + "\n"217218 isatty = False219 click.echo(styled_text)220 out, err = capfd.readouterr()220 assert out == text + '\n'221 assert out == text + "\n"222223223@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.")225def 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))233233 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 == ""238238 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"243243 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 == ""249249 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: "255255 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 == ""261261 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]: "267267 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: " ")270270 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 == ""275275 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"280281282def 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())288288 click.echo('meep')289 click.echo("meep")290291 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")294294 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"298298 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"302303304def test_open_file_ignore_errors_stdin(runner):305 @click.command()
32 unmodified lines
338 with click.open_file("test.bin", errors="ignore") as f:339 f.read()340341341@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,])344def 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)349350 @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()354359 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) == permissions358359364@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.")361def test_open_file_atomic_permissions_new_file(runner):362 with runner.isolated_filesystem():363364 @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()368369 # 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)374378 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) == permissions378379380def 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()387388389def 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 line
modified:setup.py+1 added-1 removed
6 unmodified lines
7with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()910with 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)1213setup(14 name="click",15 version=version,
25 unmodified lines