if len(self.ring) == <NUM_LIT:0>:<EOL><INDENT>return [None, None]<EOL><DEDENT>crc = self.hash_method(b(key))<EOL>idx = bisect.bisect(self.sorted_keys, crc)<EOL>idx = min(idx, (self.replicas * len(self.nodes)) - <NUM_LIT:1>)<EOL>return [self.ring[self.sorted_keys[idx]], idx]<EOL>

Given a string key a corresponding node in the hash ring is returned
        along with it's position in the ring.

        If the hash ring is empty, (`None`, `None`) is returned.


if len(self.ring) == <NUM_LIT:0>:<EOL><INDENT>yield None, None<EOL><DEDENT>node, pos = self.get_node_pos(key)<EOL>for k in self.sorted_keys[pos:]:<EOL><INDENT>yield k, self.ring[k]<EOL><DEDENT>

Given a string key it returns the nodes as a generator that can hold the key.


configs = []<EOL>if not isinstance(servers, list):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>_type = type(servers[<NUM_LIT:0>])<EOL>if _type == dict:<EOL><INDENT>return servers<EOL><DEDENT>if (sys.version_info[<NUM_LIT:0>] == <NUM_LIT:3> and _type in [str, bytes])or (sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2> and _type in [str, unicode]):<EOL><INDENT>for config in servers:<EOL><INDENT>configs.append(parse_url(config))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return configs<EOL>


args = list_or_args(keys, args)<EOL>server_keys = {}<EOL>ret_dict = {}<EOL>for key in args:<EOL><INDENT>server_name = self.get_server_name(key)<EOL>server_keys[server_name] = server_keys.get(server_name, [])<EOL>server_keys[server_name].append(key)<EOL><DEDENT>for server_name, sub_keys in iteritems(server_keys):<EOL><INDENT>values = self.connections[server_name].mget(sub_keys)<EOL>ret_dict.update(dict(zip(sub_keys, values)))<EOL><DEDENT>result = []<EOL>for key in args:<EOL><INDENT>result.append(ret_dict.get(key, None))<EOL><DEDENT>return result<EOL>

Returns a list of values ordered identically to ``keys``


servers = {}<EOL>for key, value in mapping.items():<EOL><INDENT>server_name = self.get_server_name(key)<EOL>servers.setdefault(server_name, [])<EOL>servers[server_name].append((key, value))<EOL><DEDENT>for name, items in servers.items():<EOL><INDENT>self.connections[name].mset(dict(items))<EOL><DEDENT>return True<EOL>

Sets each key in the ``mapping`` dict to its corresponding value


def lock(self, name, timeout=None, sleep=<NUM_LIT:0.1>):

return Lock(self, name, timeout=timeout, sleep=sleep)<EOL>

Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.

If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.

``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.


for env in list(self):<EOL><INDENT>if not env.exists:<EOL><INDENT>self.remove(env)<EOL><DEDENT><DEDENT>

Validate all the entries in the environment cache.


if not os.path.exists(self.path):<EOL><INDENT>return<EOL><DEDENT>with open(self.path, '<STR_LIT:r>') as f:<EOL><INDENT>env_data = yaml.load(f.read())<EOL><DEDENT>if env_data:<EOL><INDENT>for env in env_data:<EOL><INDENT>self.add(VirtualEnvironment(env['<STR_LIT:root>']))<EOL><DEDENT><DEDENT>


for env in list(self):<EOL><INDENT>self.remove(env)<EOL><DEDENT>


env_data = [dict(name=env.name, root=env.path) for env in self]<EOL>encode = yaml.safe_dump(env_data, default_flow_style=False)<EOL>with open(self.path, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(encode)<EOL><DEDENT>


if isinstance(path, VirtualEnvironment):<EOL><INDENT>return path<EOL><DEDENT>raise ResolveError<EOL>

Checks if path is already a VirtualEnvironment


path = unipath(path)<EOL>if is_environment(path):<EOL><INDENT>return VirtualEnvironment(path)<EOL><DEDENT>raise ResolveError<EOL>

Resolves VirtualEnvironments with a relative or absolute path


from .api import get_home_path<EOL>path = unipath(get_home_path(), path)<EOL>if is_environment(path):<EOL><INDENT>return VirtualEnvironment(path)<EOL><DEDENT>raise ResolveError<EOL>

Resolves VirtualEnvironments in CPENV_HOME


env = resolver.cache.find(path)<EOL>if env:<EOL><INDENT>return env<EOL><DEDENT>raise ResolveError<EOL>

Resolves VirtualEnvironments in EnvironmentCache


if isinstance(path, Module):<EOL><INDENT>return path<EOL><DEDENT>raise ResolveError<EOL>

Checks if path is already a :class:`Module` object


if resolver.resolved:<EOL><INDENT>if isinstance(resolver.resolved[<NUM_LIT:0>], VirtualEnvironment):<EOL><INDENT>env = resolver.resolved[<NUM_LIT:0>]<EOL>mod = env.get_module(path)<EOL>if mod:<EOL><INDENT>return mod<EOL><DEDENT><DEDENT><DEDENT>raise ResolveError<EOL>

Resolves module in previously resolved environment.


from .api import get_module_paths<EOL>for module_dir in get_module_paths():<EOL><INDENT>mod_path = unipath(module_dir, path)<EOL>if is_module(mod_path):<EOL><INDENT>return Module(mod_path)<EOL><DEDENT><DEDENT>raise ResolveError<EOL>

Resolves modules in CPENV_MODULES path and CPENV_HOME/modules


from .api import get_active_env<EOL>env = get_active_env()<EOL>if not env:<EOL><INDENT>raise ResolveError<EOL><DEDENT>mod = env.get_module(path)<EOL>if not mod:<EOL><INDENT>raise ResolveError<EOL><DEDENT>return mod<EOL>

Resolves modules in currently active environment.


if not os.path.exists(path):<EOL><INDENT>raise ResolveError<EOL><DEDENT>if os.path.isfile(path):<EOL><INDENT>path = os.path.dirname(path)<EOL><DEDENT>for root, _, _ in walk_up(path):<EOL><INDENT>if is_redirecting(root):<EOL><INDENT>env_paths = redirect_to_env_paths(unipath(root, '<STR_LIT>'))<EOL>r = Resolver(*env_paths)<EOL>return r.resolve()<EOL><DEDENT><DEDENT>raise ResolveError<EOL>

Resolves environment from .cpenv file...recursively walks up the tree
    in attempt to find a .cpenv file


<EOL>if isinstance(obj, cpenv.VirtualEnvironment):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>' if obj.parent else '<STR_LIT>'<EOL>

Get the type or classification of an environment or module


return isinstance(obj, cpenv.Module), obj.name<EOL>

Sort key for a list of environments and modules


def format_objects(objects, children=False, columns=None, header=True):

columns = columns or ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>objects = sorted(objects, key=_type_and_name)<EOL>data = []<EOL>for obj in objects:<EOL><INDENT>if isinstance(obj, cpenv.VirtualEnvironment):<EOL><INDENT>data.append(get_info(obj))<EOL>modules = obj.get_modules()<EOL>if children and modules:<EOL><INDENT>for mod in modules:<EOL><INDENT>data.append(get_info(mod, indent=<NUM_LIT:2>, root=obj.path))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>data.append(get_info(obj))<EOL><DEDENT><DEDENT>maxes = [len(max(col, key=len)) for col in zip(*data)]<EOL>tmpl = '<STR_LIT>' % tuple(maxes)<EOL>lines = []<EOL>if header:<EOL><INDENT>lines.append('<STR_LIT:\n>' + bold_blue(tmpl.format(*columns)))<EOL><DEDENT>for obj_data in data:<EOL><INDENT>lines.append(tmpl.format(*obj_data))<EOL><DEDENT>return '<STR_LIT:\n>'.join(lines)<EOL>

Format a list of environments and modules for terminal output


EnvironmentCache.validate()<EOL>


env = cpenv.get_active_env()<EOL>modules = []<EOL>if env:<EOL><INDENT>modules = env.get_modules()<EOL><DEDENT>active_modules = cpenv.get_active_modules()<EOL>if not env and not modules and not active_modules:<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>click.echo(bold('<STR_LIT>'))<EOL>if env:<EOL><INDENT>click.echo(format_objects([env] + active_modules))<EOL>available_modules = set(modules) - set(active_modules)<EOL>if available_modules:<EOL><INDENT>click.echo(<EOL>bold('<STR_LIT>').format(cyan(env.name))<EOL>)<EOL>click.echo(format_objects(available_modules, header=False))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>click.echo(format_objects(active_modules))<EOL><DEDENT>available_shared_modules = set(cpenv.get_modules()) - set(active_modules)<EOL>if not available_shared_modules:<EOL><INDENT>return<EOL><DEDENT>click.echo(bold('<STR_LIT>'))<EOL>click.echo(format_objects(available_shared_modules, header=False))<EOL>


environments = cpenv.get_environments()<EOL>modules = cpenv.get_modules()<EOL>click.echo(format_objects(environments + modules, children=True))<EOL>


@cli.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.option('<STR_LIT>', is_flag=True, help='<STR_LIT>')<EOL>@click.option('<STR_LIT>', is_flag=True, help='<STR_LIT>')<EOL>def activate(paths, skip_local, skip_shared):

if not paths:<EOL><INDENT>ctx = click.get_current_context()<EOL>if cpenv.get_active_env():<EOL><INDENT>ctx.invoke(info)<EOL>return<EOL><DEDENT>click.echo(ctx.get_help())<EOL>examples = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>click.echo(examples)<EOL>return<EOL><DEDENT>if skip_local:<EOL><INDENT>cpenv.module_resolvers.remove(cpenv.resolver.module_resolver)<EOL>cpenv.module_resolvers.remove(cpenv.resolver.active_env_module_resolver)<EOL><DEDENT>if skip_shared:<EOL><INDENT>cpenv.module_resolvers.remove(cpenv.resolver.modules_path_resolver)<EOL><DEDENT>try:<EOL><INDENT>r = cpenv.resolve(*paths)<EOL><DEDENT>except cpenv.ResolveError as e:<EOL><INDENT>click.echo('<STR_LIT:\n>' + str(e))<EOL>return<EOL><DEDENT>resolved = set(r.resolved)<EOL>active_modules = set()<EOL>env = cpenv.get_active_env()<EOL>if env:<EOL><INDENT>active_modules.add(env)<EOL><DEDENT>active_modules.update(cpenv.get_active_modules())<EOL>new_modules = resolved - active_modules<EOL>old_modules = active_modules & resolved<EOL>if old_modules and not new_modules:<EOL><INDENT>click.echo(<EOL>'<STR_LIT>'<EOL>+ bold('<STR_LIT:U+0020>'.join([obj.name for obj in old_modules]))<EOL>)<EOL>return<EOL><DEDENT>if env and contains_env(new_modules):<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>click.echo('<STR_LIT>')<EOL>click.echo(format_objects(r.resolved))<EOL>r.activate()<EOL>click.echo(blue('<STR_LIT>'))<EOL>modules = sorted(resolved | active_modules, key=_type_and_name)<EOL>prompt = '<STR_LIT::>'.join([obj.name for obj in modules])<EOL>shell.launch(prompt)<EOL>


@cli.command()<EOL>@click.argument('<STR_LIT>', required=False)<EOL>@click.option('<STR_LIT>', help='<STR_LIT>')<EOL>def create(name_or_path, config):

if not name_or_path:<EOL><INDENT>ctx = click.get_current_context()<EOL>click.echo(ctx.get_help())<EOL>examples = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>click.echo(examples)<EOL>return<EOL><DEDENT>click.echo(<EOL>blue('<STR_LIT>' + name_or_path)<EOL>)<EOL>try:<EOL><INDENT>env = cpenv.create(name_or_path, config)<EOL><DEDENT>except Exception as e:<EOL><INDENT>click.echo(bold_red('<STR_LIT>'))<EOL>click.echo(e)<EOL><DEDENT>else:<EOL><INDENT>click.echo(bold_green('<STR_LIT>'))<EOL><DEDENT>click.echo(blue('<STR_LIT>'))<EOL>cpenv.activate(env)<EOL>shell.launch(env.name)<EOL>


click.echo()<EOL>try:<EOL><INDENT>r = cpenv.resolve(name_or_path)<EOL><DEDENT>except cpenv.ResolveError as e:<EOL><INDENT>click.echo(e)<EOL>return<EOL><DEDENT>obj = r.resolved[<NUM_LIT:0>]<EOL>if not isinstance(obj, cpenv.VirtualEnvironment):<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>click.echo(format_objects([obj]))<EOL>click.echo()<EOL>user_confirmed = click.confirm(<EOL>red('<STR_LIT>')<EOL>)<EOL>if user_confirmed:<EOL><INDENT>click.echo('<STR_LIT>', nl=False)<EOL>try:<EOL><INDENT>obj.remove()<EOL><DEDENT>except Exception as e:<EOL><INDENT>click.echo(bold_red('<STR_LIT>'))<EOL>click.echo(e)<EOL><DEDENT>else:<EOL><INDENT>click.echo(bold_green('<STR_LIT>'))<EOL><DEDENT><DEDENT>


click.echo('<STR_LIT>')<EOL>environments = list(EnvironmentCache)<EOL>click.echo(format_objects(environments, children=False))<EOL>


click.echo('<STR_LIT>'.format(path), nl=False)<EOL>try:<EOL><INDENT>r = cpenv.resolve(path)<EOL><DEDENT>except Exception as e:<EOL><INDENT>click.echo(bold_red('<STR_LIT>'))<EOL>click.echo(e)<EOL>return<EOL><DEDENT>if isinstance(r.resolved[<NUM_LIT:0>], cpenv.VirtualEnvironment):<EOL><INDENT>EnvironmentCache.add(r.resolved[<NUM_LIT:0>])<EOL>EnvironmentCache.save()<EOL>click.echo(bold_green('<STR_LIT>'))<EOL><DEDENT>

Add an environment to the cache. Allows you to activate the environment
    by name instead of by full path


r = cpenv.resolve(path)<EOL>if isinstance(r.resolved[<NUM_LIT:0>], cpenv.VirtualEnvironment):<EOL><INDENT>EnvironmentCache.discard(r.resolved[<NUM_LIT:0>])<EOL>EnvironmentCache.save()<EOL><DEDENT>

Remove a cached environment. Removed paths will no longer be able to
    be activated by name


if click.confirm('<STR_LIT>'):<EOL><INDENT>cpenv.EnvironmentCache.clear()<EOL>click.echo('<STR_LIT>')<EOL><DEDENT>


Create a new template module.

    You can also specify a filesystem path like "./modules/new_module"


if not name and not path:<EOL><INDENT>ctx = click.get_current_context()<EOL>click.echo(ctx.get_help())<EOL>examples = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>click.echo(examples)<EOL>return<EOL><DEDENT>if not name:<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>if not path:<EOL><INDENT>click.echo('<STR_LIT>')<EOL><DEDENT>env = cpenv.get_active_env()<EOL>if type=='<STR_LIT>':<EOL><INDENT>if not env:<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>if click.confirm('<STR_LIT>'.format(name, env.name)):<EOL><INDENT>click.echo('<STR_LIT>', nl=False)<EOL>try:<EOL><INDENT>env.add_module(name, path, branch)<EOL><DEDENT>except:<EOL><INDENT>click.echo(bold_red('<STR_LIT>'))<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>click.echo(bold_green('<STR_LIT>'))<EOL><DEDENT><DEDENT>return<EOL><DEDENT>module_paths = cpenv.get_module_paths()<EOL>click.echo('<STR_LIT>')<EOL>for i, mod_path in enumerate(module_paths):<EOL><INDENT>click.echo('<STR_LIT>'.format(i, mod_path))<EOL><DEDENT>choice = click.prompt(<EOL>'<STR_LIT>',<EOL>type=int,<EOL>default=<NUM_LIT:0><EOL>)<EOL>module_root = module_paths[choice]<EOL>module_path = utils.unipath(module_root, name)<EOL>click.echo('<STR_LIT>'.format(module_path), nl=False)<EOL>try:<EOL><INDENT>cpenv.create_module(module_path, path, branch)<EOL><DEDENT>except:<EOL><INDENT>click.echo(bold_red('<STR_LIT>'))<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>click.echo(bold_green('<STR_LIT>'))<EOL><DEDENT>

Add a module to an environment. PATH can be a git repository path or
    a filesystem path.


@module.command()<EOL>@click.argument('<STR_LIT:name>')<EOL>@click.option('<STR_LIT>', is_flag=True, help='<STR_LIT>')<EOL>def remove(name, local):

click.echo()<EOL>if not local: <EOL><INDENT>try:<EOL><INDENT>r = cpenv.resolve(name)<EOL><DEDENT>except cpenv.ResolveError as e:<EOL><INDENT>click.echo(e)<EOL>return<EOL><DEDENT>obj = r.resolved[<NUM_LIT:0>]<EOL><DEDENT>else: <EOL><INDENT>env = cpenv.get_active_env()<EOL>if not env:<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>mod = env.get_module(name)<EOL>if not mod:<EOL><INDENT>click.echo('<STR_LIT>' + name)<EOL>return<EOL><DEDENT>obj = mod<EOL><DEDENT>if isinstance(obj, cpenv.VirtualEnvironment):<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>click.echo(format_objects([obj]))<EOL>click.echo()<EOL>user_confirmed = click.confirm(<EOL>red('<STR_LIT>')<EOL>)<EOL>if user_confirmed:<EOL><INDENT>click.echo('<STR_LIT>', nl=False)<EOL>try:<EOL><INDENT>obj.remove()<EOL><DEDENT>except Exception as e:<EOL><INDENT>click.echo(bold_red('<STR_LIT>'))<EOL>click.echo(e)<EOL><DEDENT>else:<EOL><INDENT>click.echo(bold_green('<STR_LIT>'))<EOL><DEDENT><DEDENT>

Remove a module named NAME. Will remove the first resolved module named NAME. You can also specify a full path to a module. Use the --local option
    to ensure removal of modules local to the currently active environment.


env = cpenv.get_active_env()<EOL>if not env:<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>try:<EOL><INDENT>r = cpenv.resolve(name)<EOL><DEDENT>except cpenv.ResolveError as e:<EOL><INDENT>click.echo('<STR_LIT:\n>' + str(e))<EOL><DEDENT>module = r.resolved[<NUM_LIT:0>]<EOL>if isinstance(module, cpenv.VirtualEnvironment):<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>active_modules = cpenv.get_active_modules()<EOL>if module in active_modules:<EOL><INDENT>click.echo('<STR_LIT>')<EOL>return<EOL><DEDENT>if module in env.get_modules():<EOL><INDENT>click.echo('<STR_LIT>'.format(module.name, env.name))<EOL>return<EOL><DEDENT>if click.confirm('<STR_LIT>'.format(module.name, env.name)):<EOL><INDENT>click.echo('<STR_LIT>', nl=False)<EOL>try:<EOL><INDENT>module = env.add_module(module.name, module.path)<EOL><DEDENT>except:<EOL><INDENT>click.echo(bold_red('<STR_LIT>'))<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>click.echo(bold_green('<STR_LIT>'))<EOL><DEDENT><DEDENT>click.echo('<STR_LIT>')<EOL>click.echo('<STR_LIT>'.format(env.name, module.name))<EOL>

Copy a global module to the active environment.


return self.convert or self.strip or self.autoreset<EOL>

True if this class is actually needed. If false, then the output
stream will not be affected, nor will win32 calls be issued, so
wrapping stdout is not actually required. This will generally be
False on non-Windows platforms, unless optional functionality like
autoreset has been requested using kwargs to init()


cursor = <NUM_LIT:0><EOL>text = self.convert_osc(text)<EOL>for match in self.ANSI_CSI_RE.finditer(text):<EOL><INDENT>start, end = match.span()<EOL>self.write_plain_text(text, cursor, start)<EOL>self.convert_ansi(*match.groups())<EOL>cursor = end<EOL><DEDENT>self.write_plain_text(text, cursor, len(text))<EOL>

Write the given text to our wrapped stream, stripping any ANSI
sequences from the text, and optionally converting them into win32
calls.


loader = Loader(stream)<EOL>try:<EOL><INDENT>while loader.check_token():<EOL><INDENT>yield loader.get_token()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>

Scan a YAML stream and produce scanning tokens.


loader = Loader(stream)<EOL>try:<EOL><INDENT>while loader.check_event():<EOL><INDENT>yield loader.get_event()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>

Parse a YAML stream and produce parsing events.


loader = Loader(stream)<EOL>try:<EOL><INDENT>return loader.get_single_node()<EOL><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>

Parse the first YAML document in a stream
and produce the corresponding representation tree.


loader = Loader(stream)<EOL>try:<EOL><INDENT>while loader.check_node():<EOL><INDENT>yield loader.get_node()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>

Parse all YAML documents in a stream
and produce corresponding representation trees.


loader = Loader(stream)<EOL>try:<EOL><INDENT>return loader.get_single_data()<EOL><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>

Parse the first YAML document in a stream
and produce the corresponding Python object.


loader = Loader(stream)<EOL>try:<EOL><INDENT>while loader.check_data():<EOL><INDENT>yield loader.get_data()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>loader.dispose()<EOL><DEDENT>

Parse all YAML documents in a stream
and produce corresponding Python objects.


return load(stream, SafeLoader)<EOL>

Parse the first YAML document in a stream
and produce the corresponding Python object.
Resolve only basic YAML tags.


return load_all(stream, SafeLoader)<EOL>

Parse all YAML documents in a stream
and produce corresponding Python objects.
Resolve only basic YAML tags.


def emit(events, stream=None, Dumper=Dumper,<EOL>canonical=None, indent=None, width=None,<EOL>allow_unicode=None, line_break=None):

getvalue = None<EOL>if stream is None:<EOL><INDENT>from StringIO import StringIO<EOL>stream = StringIO()<EOL>getvalue = stream.getvalue<EOL><DEDENT>dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,<EOL>allow_unicode=allow_unicode, line_break=line_break)<EOL>try:<EOL><INDENT>for event in events:<EOL><INDENT>dumper.emit(event)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>dumper.dispose()<EOL><DEDENT>if getvalue:<EOL><INDENT>return getvalue()<EOL><DEDENT>

Emit YAML parsing events into a stream.
If stream is None, return the produced string instead.


def serialize_all(nodes, stream=None, Dumper=Dumper,<EOL>canonical=None, indent=None, width=None,<EOL>allow_unicode=None, line_break=None,<EOL>encoding='<STR_LIT:utf-8>', explicit_start=None, explicit_end=None,<EOL>version=None, tags=None):

getvalue = None<EOL>if stream is None:<EOL><INDENT>if encoding is None:<EOL><INDENT>from StringIO import StringIO<EOL><DEDENT>else:<EOL><INDENT>from cStringIO import StringIO<EOL><DEDENT>stream = StringIO()<EOL>getvalue = stream.getvalue<EOL><DEDENT>dumper = Dumper(stream, canonical=canonical, indent=indent, width=width,<EOL>allow_unicode=allow_unicode, line_break=line_break,<EOL>encoding=encoding, version=version, tags=tags,<EOL>explicit_start=explicit_start, explicit_end=explicit_end)<EOL>try:<EOL><INDENT>dumper.open()<EOL>for node in nodes:<EOL><INDENT>dumper.serialize(node)<EOL><DEDENT>dumper.close()<EOL><DEDENT>finally:<EOL><INDENT>dumper.dispose()<EOL><DEDENT>if getvalue:<EOL><INDENT>return getvalue()<EOL><DEDENT>

Serialize a sequence of representation trees into a YAML stream.
If stream is None, return the produced string instead.


def serialize(node, stream=None, Dumper=Dumper, **kwds):

return serialize_all([node], stream, Dumper=Dumper, **kwds)<EOL>

Serialize a representation tree into a YAML stream.
If stream is None, return the produced string instead.


def dump_all(documents, stream=None, Dumper=Dumper,<EOL>default_style=None, default_flow_style=None,<EOL>canonical=None, indent=None, width=None,<EOL>allow_unicode=None, line_break=None,<EOL>encoding='<STR_LIT:utf-8>', explicit_start=None, explicit_end=None,<EOL>version=None, tags=None):

getvalue = None<EOL>if stream is None:<EOL><INDENT>if encoding is None:<EOL><INDENT>from StringIO import StringIO<EOL><DEDENT>else:<EOL><INDENT>from cStringIO import StringIO<EOL><DEDENT>stream = StringIO()<EOL>getvalue = stream.getvalue<EOL><DEDENT>dumper = Dumper(stream, default_style=default_style,<EOL>default_flow_style=default_flow_style,<EOL>canonical=canonical, indent=indent, width=width,<EOL>allow_unicode=allow_unicode, line_break=line_break,<EOL>encoding=encoding, version=version, tags=tags,<EOL>explicit_start=explicit_start, explicit_end=explicit_end)<EOL>try:<EOL><INDENT>dumper.open()<EOL>for data in documents:<EOL><INDENT>dumper.represent(data)<EOL><DEDENT>dumper.close()<EOL><DEDENT>finally:<EOL><INDENT>dumper.dispose()<EOL><DEDENT>if getvalue:<EOL><INDENT>return getvalue()<EOL><DEDENT>

Serialize a sequence of Python objects into a YAML stream.
If stream is None, return the produced string instead.


def dump(data, stream=None, Dumper=Dumper, **kwds):

return dump_all([data], stream, Dumper=Dumper, **kwds)<EOL>

Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.


def safe_dump_all(documents, stream=None, **kwds):

return dump_all(documents, stream, Dumper=SafeDumper, **kwds)<EOL>

Serialize a sequence of Python objects into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead.


def safe_dump(data, stream=None, **kwds):

return dump_all([data], stream, Dumper=SafeDumper, **kwds)<EOL>

Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead.


def add_implicit_resolver(tag, regexp, first=None,<EOL>Loader=Loader, Dumper=Dumper):

Loader.add_implicit_resolver(tag, regexp, first)<EOL>Dumper.add_implicit_resolver(tag, regexp, first)<EOL>

Add an implicit scalar detector.
If an implicit scalar value matches the given regexp,
the corresponding tag is assigned to the scalar.
first is a sequence of possible initial characters or None.


def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):

Loader.add_path_resolver(tag, path, kind)<EOL>Dumper.add_path_resolver(tag, path, kind)<EOL>

Add a path based resolver for the given tag.
A path is a list of keys that forms a path
to a node in the representation tree.
Keys can be string values, integers, or None.


def add_constructor(tag, constructor, Loader=Loader):

Loader.add_constructor(tag, constructor)<EOL>

Add a constructor for the given tag.
Constructor is a function that accepts a Loader instance
and a node object and produces the corresponding Python object.


def add_multi_constructor(tag_prefix, multi_constructor, Loader=Loader):

Loader.add_multi_constructor(tag_prefix, multi_constructor)<EOL>

Add a multi-constructor for the given tag prefix.
Multi-constructor is called for a node if its tag starts with tag_prefix.
Multi-constructor accepts a Loader instance, a tag suffix,
and a node object and produces the corresponding Python object.


def add_representer(data_type, representer, Dumper=Dumper):

Dumper.add_representer(data_type, representer)<EOL>

Add a representer for the given type.
Representer is a function accepting a Dumper instance
and an instance of the given data type
and producing the corresponding representation node.


def add_multi_representer(data_type, multi_representer, Dumper=Dumper):

Dumper.add_multi_representer(data_type, multi_representer)<EOL>

Add a representer for the given type.
Multi-representer is a function accepting a Dumper instance
and an instance of the given data type or subtype
and producing the corresponding representation node.


return loader.construct_yaml_object(node, cls)<EOL>

Convert a representation node to a Python object.


return dumper.represent_yaml_object(cls.yaml_tag, data, cls,<EOL>flow_style=cls.yaml_flow_style)<EOL>

Convert a Python object to a representation node.


<EOL>self.done = False<EOL>self.flow_level = <NUM_LIT:0><EOL>self.tokens = []<EOL>self.fetch_stream_start()<EOL>self.tokens_taken = <NUM_LIT:0><EOL>self.indent = -<NUM_LIT:1><EOL>self.indents = []<EOL>self.allow_simple_key = True<EOL>self.possible_simple_keys = {}<EOL>


args = deque(args)<EOL>nargs_spec = deque(nargs_spec)<EOL>rv = []<EOL>spos = None<EOL>def _fetch(c):<EOL><INDENT>try:<EOL><INDENT>if spos is None:<EOL><INDENT>return c.popleft()<EOL><DEDENT>else:<EOL><INDENT>return c.pop()<EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>while nargs_spec:<EOL><INDENT>nargs = _fetch(nargs_spec)<EOL>if nargs == <NUM_LIT:1>:<EOL><INDENT>rv.append(_fetch(args))<EOL><DEDENT>elif nargs > <NUM_LIT:1>:<EOL><INDENT>x = [_fetch(args) for _ in range(nargs)]<EOL>if spos is not None:<EOL><INDENT>x.reverse()<EOL><DEDENT>rv.append(tuple(x))<EOL><DEDENT>elif nargs < <NUM_LIT:0>:<EOL><INDENT>if spos is not None:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>spos = len(rv)<EOL>rv.append(None)<EOL><DEDENT><DEDENT>if spos is not None:<EOL><INDENT>rv[spos] = tuple(args)<EOL>args = []<EOL>rv[spos + <NUM_LIT:1>:] = reversed(rv[spos + <NUM_LIT:1>:])<EOL><DEDENT>return tuple(rv), list(args)<EOL>

Given an iterable of arguments and an iterable of nargs specifications,
    it returns a tuple with all the unpacked arguments at the first index
    and all remaining arguments as the second.

    The nargs specification is the number of arguments that should be consumed
    or `-1` to indicate that this position should eat up all the remainders.

    Missing items are filled with `None`.


rv = []<EOL>for match in re.finditer(r"<STR_LIT>"<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>', string, re.S):<EOL><INDENT>arg = match.group().strip()<EOL>if arg[:<NUM_LIT:1>] == arg[-<NUM_LIT:1>:] and arg[:<NUM_LIT:1>] in '<STR_LIT>':<EOL><INDENT>arg = arg[<NUM_LIT:1>:-<NUM_LIT:1>].encode('<STR_LIT:ascii>', '<STR_LIT>').decode('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>arg = type(string)(arg)<EOL><DEDENT>except UnicodeError:<EOL><INDENT>pass<EOL><DEDENT>rv.append(arg)<EOL><DEDENT>return rv<EOL>

Given an argument string this attempts to split it into small parts.


def add_option(self, opts, dest, action=None, nargs=<NUM_LIT:1>, const=None,<EOL>obj=None):

if obj is None:<EOL><INDENT>obj = dest<EOL><DEDENT>opts = [normalize_opt(opt, self.ctx) for opt in opts]<EOL>option = Option(opts, dest, action=action, nargs=nargs,<EOL>const=const, obj=obj)<EOL>self._opt_prefixes.update(option.prefixes)<EOL>for opt in option._short_opts:<EOL><INDENT>self._short_opt[opt] = option<EOL><DEDENT>for opt in option._long_opts:<EOL><INDENT>self._long_opt[opt] = option<EOL><DEDENT>

Adds a new option named `dest` to the parser.  The destination
        is not inferred (unlike with optparse) and needs to be explicitly
        provided.  Action can be any of ``store``, ``store_const``,
        ``append``, ``appnd_const`` or ``count``.

        The `obj` can be used to identify the option in the order list
        that is returned from the parser.


def add_argument(self, dest, nargs=<NUM_LIT:1>, obj=None):

if obj is None:<EOL><INDENT>obj = dest<EOL><DEDENT>self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))<EOL>

Adds a positional argument named `dest` to the parser.

        The `obj` can be used to identify the option in the order list
        that is returned from the parser.


state = ParsingState(args)<EOL>try:<EOL><INDENT>self._process_args_for_options(state)<EOL>self._process_args_for_args(state)<EOL><DEDENT>except UsageError:<EOL><INDENT>if self.ctx is None or not self.ctx.resilient_parsing:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>return state.opts, state.largs, state.order<EOL>

Parses positional arguments and returns ``(values, args, order)``
        for the parsed options and arguments as well as the leftover
        arguments if there are any.  The order is a list of objects as they
        appear on the command line.  If arguments appear multiple times they
        will be memorized multiple times as well.


try:<EOL><INDENT>return getattr(_local, '<STR_LIT>')[-<NUM_LIT:1>]<EOL><DEDENT>except (AttributeError, IndexError):<EOL><INDENT>if not silent:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT><DEDENT>

Returns the current click context.  This can be used as a way to
    access the current context object from anywhere.  This is a more implicit
    alternative to the :func:`pass_context` decorator.  This function is
    primarily useful for helpers such as :func:`echo` which might be
    interested in changing it's behavior based on the current context.

    To push the current context, :meth:`Context.scope` can be used.

    .. versionadded:: 5.0

    :param silent: is set to `True` the return value is `None` if no context
                   is available.  The default behavior is to raise a
                   :exc:`RuntimeError`.


_local.__dict__.setdefault('<STR_LIT>', []).append(ctx)<EOL>

Pushes a new context to the current stack.


if color is not None:<EOL><INDENT>return color<EOL><DEDENT>ctx = get_current_context(silent=True)<EOL>if ctx is not None:<EOL><INDENT>return ctx.color<EOL><DEDENT>

Internal helper to get the default value of the color flag.  If a
    value is passed it's returned unchanged, otherwise it's looked up from
    the current context.


try:<EOL><INDENT>return len(obj)<EOL><DEDENT>except (AttributeError, TypeError):<EOL><INDENT>try:<EOL><INDENT>get_hint = type(obj).__length_hint__<EOL><DEDENT>except AttributeError:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>hint = get_hint(obj)<EOL><DEDENT>except TypeError:<EOL><INDENT>return None<EOL><DEDENT>if hint is NotImplemented ornot isinstance(hint, (int, long)) orhint < <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return hint<EOL><DEDENT>


stdout = _default_text_stdout()<EOL>if not isatty(sys.stdin) or not isatty(stdout):<EOL><INDENT>return _nullpager(stdout, text, color)<EOL><DEDENT>pager_cmd = (os.environ.get('<STR_LIT>', None) or '<STR_LIT>').strip()<EOL>if pager_cmd:<EOL><INDENT>if WIN:<EOL><INDENT>return _tempfilepager(text, pager_cmd, color)<EOL><DEDENT>return _pipepager(text, pager_cmd, color)<EOL><DEDENT>if os.environ.get('<STR_LIT>') in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return _nullpager(stdout, text, color)<EOL><DEDENT>if WIN or sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>return _tempfilepager(text, '<STR_LIT>', color)<EOL><DEDENT>if hasattr(os, '<STR_LIT>') and os.system('<STR_LIT>') == <NUM_LIT:0>:<EOL><INDENT>return _pipepager(text, '<STR_LIT>', color)<EOL><DEDENT>import tempfile<EOL>fd, filename = tempfile.mkstemp()<EOL>os.close(fd)<EOL>try:<EOL><INDENT>if hasattr(os, '<STR_LIT>') and os.system('<STR_LIT>' % filename) == <NUM_LIT:0>:<EOL><INDENT>return _pipepager(text, '<STR_LIT>', color)<EOL><DEDENT>return _nullpager(stdout, text, color)<EOL><DEDENT>finally:<EOL><INDENT>os.unlink(filename)<EOL><DEDENT>

Decide what method to use for paging through text.


import subprocess<EOL>env = dict(os.environ)<EOL>cmd_detail = cmd.rsplit('<STR_LIT:/>', <NUM_LIT:1>)[-<NUM_LIT:1>].split()<EOL>if color is None and cmd_detail[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>less_flags = os.environ.get('<STR_LIT>', '<STR_LIT>') + '<STR_LIT:U+0020>'.join(cmd_detail[<NUM_LIT:1>:])<EOL>if not less_flags:<EOL><INDENT>env['<STR_LIT>'] = '<STR_LIT>'<EOL>color = True<EOL><DEDENT>elif '<STR_LIT:r>' in less_flags or '<STR_LIT:R>' in less_flags:<EOL><INDENT>color = True<EOL><DEDENT><DEDENT>if not color:<EOL><INDENT>text = strip_ansi(text)<EOL><DEDENT>c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,<EOL>env=env)<EOL>encoding = get_best_encoding(c.stdin)<EOL>try:<EOL><INDENT>c.stdin.write(text.encode(encoding, '<STR_LIT:replace>'))<EOL>c.stdin.close()<EOL><DEDENT>except (IOError, KeyboardInterrupt):<EOL><INDENT>pass<EOL><DEDENT>while True:<EOL><INDENT>try:<EOL><INDENT>c.wait()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Page through text by feeding it to another program.  Invoking a
    pager through this might support colors.


import tempfile<EOL>filename = tempfile.mktemp()<EOL>if not color:<EOL><INDENT>text = strip_ansi(text)<EOL><DEDENT>encoding = get_best_encoding(sys.stdout)<EOL>with open_stream(filename, '<STR_LIT:wb>')[<NUM_LIT:0>] as f:<EOL><INDENT>f.write(text.encode(encoding))<EOL><DEDENT>try:<EOL><INDENT>os.system(cmd + '<STR_LIT>' + filename + '<STR_LIT:">')<EOL><DEDENT>finally:<EOL><INDENT>os.unlink(filename)<EOL><DEDENT>

Page through text by invoking a program on a temporary file.


if not color:<EOL><INDENT>text = strip_ansi(text)<EOL><DEDENT>stream.write(text)<EOL>

Simply print unformatted text.  This is the ultimate fallback.


try:<EOL><INDENT>return codecs.lookup(encoding).name == '<STR_LIT:ascii>'<EOL><DEDENT>except LookupError:<EOL><INDENT>return False<EOL><DEDENT>


rv = getattr(stream, '<STR_LIT>', None) or sys.getdefaultencoding()<EOL>if is_ascii_encoding(rv):<EOL><INDENT>return '<STR_LIT:utf-8>'<EOL><DEDENT>return rv<EOL>

Returns the default stream encoding if not found.


return self.output_bytes.decode(self.runner.charset, '<STR_LIT:replace>').replace('<STR_LIT:\r\n>', '<STR_LIT:\n>')<EOL>


return cli.name or '<STR_LIT:root>'<EOL>

Given a command object it will return the default program name
        for it.  The default is the `name` attribute or ``"root"`` if not
        set.


rv = dict(self.env)<EOL>if overrides:<EOL><INDENT>rv.update(overrides)<EOL><DEDENT>return rv<EOL>

Returns the environment overrides for invoking a script.


@contextlib.contextmanager<EOL><INDENT>def isolation(self, input=None, env=None, color=False):<DEDENT>

input = make_input_stream(input, self.charset)<EOL>old_stdin = sys.stdin<EOL>old_stdout = sys.stdout<EOL>old_stderr = sys.stderr<EOL>old_forced_width = clickpkg.formatting.FORCED_WIDTH<EOL>clickpkg.formatting.FORCED_WIDTH = <NUM_LIT><EOL>env = self.make_env(env)<EOL>if PY2:<EOL><INDENT>sys.stdout = sys.stderr = bytes_output = StringIO()<EOL>if self.echo_stdin:<EOL><INDENT>input = EchoingStdin(input, bytes_output)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>bytes_output = io.BytesIO()<EOL>if self.echo_stdin:<EOL><INDENT>input = EchoingStdin(input, bytes_output)<EOL><DEDENT>input = io.TextIOWrapper(input, encoding=self.charset)<EOL>sys.stdout = sys.stderr = io.TextIOWrapper(<EOL>bytes_output, encoding=self.charset)<EOL><DEDENT>sys.stdin = input<EOL>def visible_input(prompt=None):<EOL><INDENT>sys.stdout.write(prompt or '<STR_LIT>')<EOL>val = input.readline().rstrip('<STR_LIT:\r\n>')<EOL>sys.stdout.write(val + '<STR_LIT:\n>')<EOL>sys.stdout.flush()<EOL>return val<EOL><DEDENT>def hidden_input(prompt=None):<EOL><INDENT>sys.stdout.write((prompt or '<STR_LIT>') + '<STR_LIT:\n>')<EOL>sys.stdout.flush()<EOL>return input.readline().rstrip('<STR_LIT:\r\n>')<EOL><DEDENT>def _getchar(echo):<EOL><INDENT>char = sys.stdin.read(<NUM_LIT:1>)<EOL>if echo:<EOL><INDENT>sys.stdout.write(char)<EOL>sys.stdout.flush()<EOL><DEDENT>return char<EOL><DEDENT>default_color = color<EOL>def should_strip_ansi(stream=None, color=None):<EOL><INDENT>if color is None:<EOL><INDENT>return not default_color<EOL><DEDENT>return not color<EOL><DEDENT>old_visible_prompt_func = clickpkg.termui.visible_prompt_func<EOL>old_hidden_prompt_func = clickpkg.termui.hidden_prompt_func<EOL>old__getchar_func = clickpkg.termui._getchar<EOL>old_should_strip_ansi = clickpkg.utils.should_strip_ansi<EOL>clickpkg.termui.visible_prompt_func = visible_input<EOL>clickpkg.termui.hidden_prompt_func = hidden_input<EOL>clickpkg.termui._getchar = _getchar<EOL>clickpkg.utils.should_strip_ansi = should_strip_ansi<EOL>old_env = {}<EOL>try:<EOL><INDENT>for key, value in iteritems(env):<EOL><INDENT>old_env[key] = os.environ.get(key)<EOL>if value is None:<EOL><INDENT>try:<EOL><INDENT>del os.environ[key]<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>os.environ[key] = value<EOL><DEDENT><DEDENT>yield bytes_output<EOL><DEDENT>finally:<EOL><INDENT>for key, value in iteritems(old_env):<EOL><INDENT>if value is None:<EOL><INDENT>try:<EOL><INDENT>del os.environ[key]<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>os.environ[key] = value<EOL><DEDENT><DEDENT>sys.stdout = old_stdout<EOL>sys.stderr = old_stderr<EOL>sys.stdin = old_stdin<EOL>clickpkg.termui.visible_prompt_func = old_visible_prompt_func<EOL>clickpkg.termui.hidden_prompt_func = old_hidden_prompt_func<EOL>clickpkg.termui._getchar = old__getchar_func<EOL>clickpkg.utils.should_strip_ansi = old_should_strip_ansi<EOL>clickpkg.formatting.FORCED_WIDTH = old_forced_width<EOL><DEDENT>

A context manager that sets up the isolation for invoking of a
        command line tool.  This sets up stdin with the given input data
        and `os.environ` with the overrides from the given dictionary.
        This also rebinds some internals in Click to be mocked (like the
        prompt functionality).

        This is automatically done in the :meth:`invoke` method.

        .. versionadded:: 4.0
           The ``color`` parameter was added.

        :param input: the input stream to put into sys.stdin.
        :param env: the environment overrides as dictionary.
        :param color: whether the output should contain color codes. The
                      application can still override this explicitly.


def invoke(self, cli, args=None, input=None, env=None,<EOL>catch_exceptions=True, color=False, **extra):

exc_info = None<EOL>with self.isolation(input=input, env=env, color=color) as out:<EOL><INDENT>exception = None<EOL>exit_code = <NUM_LIT:0><EOL>try:<EOL><INDENT>cli.main(args=args or (),<EOL>prog_name=self.get_default_prog_name(cli), **extra)<EOL><DEDENT>except SystemExit as e:<EOL><INDENT>if e.code != <NUM_LIT:0>:<EOL><INDENT>exception = e<EOL><DEDENT>exc_info = sys.exc_info()<EOL>exit_code = e.code<EOL>if not isinstance(exit_code, int):<EOL><INDENT>sys.stdout.write(str(exit_code))<EOL>sys.stdout.write('<STR_LIT:\n>')<EOL>exit_code = <NUM_LIT:1><EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>if not catch_exceptions:<EOL><INDENT>raise<EOL><DEDENT>exception = e<EOL>exit_code = -<NUM_LIT:1><EOL>exc_info = sys.exc_info()<EOL><DEDENT>finally:<EOL><INDENT>sys.stdout.flush()<EOL>output = out.getvalue()<EOL><DEDENT><DEDENT>return Result(runner=self,<EOL>output_bytes=output,<EOL>exit_code=exit_code,<EOL>exception=exception,<EOL>exc_info=exc_info)<EOL>

Invokes a command in an isolated environment.  The arguments are
        forwarded directly to the command line script, the `extra` keyword
        arguments are passed to the :meth:`~clickpkg.Command.main` function of
        the command.

        This returns a :class:`Result` object.

        .. versionadded:: 3.0
           The ``catch_exceptions`` parameter was added.

        .. versionchanged:: 3.0
           The result object now has an `exc_info` attribute with the
           traceback if available.

        .. versionadded:: 4.0
           The ``color`` parameter was added.

        :param cli: the command to invoke
        :param args: the arguments to invoke
        :param input: the input data for `sys.stdin`.
        :param env: the environment overrides.
        :param catch_exceptions: Whether to catch any other exceptions than
                                 ``SystemExit``.
        :param extra: the keyword arguments to pass to :meth:`main`.
        :param color: whether the output should contain color codes. The
                      application can still override this explicitly.


cwd = os.getcwd()<EOL>t = tempfile.mkdtemp()<EOL>os.chdir(t)<EOL>try:<EOL><INDENT>yield t<EOL><DEDENT>finally:<EOL><INDENT>os.chdir(cwd)<EOL>try:<EOL><INDENT>shutil.rmtree(t)<EOL><DEDENT>except (OSError, IOError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

A context manager that creates a temporary folder and changes
        the current working directory to it for isolated filesystem tests.


guessed_type = False<EOL>if ty is None and default is not None:<EOL><INDENT>if isinstance(default, tuple):<EOL><INDENT>ty = tuple(map(type, default))<EOL><DEDENT>else:<EOL><INDENT>ty = type(default)<EOL><DEDENT>guessed_type = True<EOL><DEDENT>if isinstance(ty, tuple):<EOL><INDENT>return Tuple(ty)<EOL><DEDENT>if isinstance(ty, ParamType):<EOL><INDENT>return ty<EOL><DEDENT>if ty is text_type or ty is str or ty is None:<EOL><INDENT>return STRING<EOL><DEDENT>if ty is int:<EOL><INDENT>return INT<EOL><DEDENT>if ty is bool and not guessed_type:<EOL><INDENT>return BOOL<EOL><DEDENT>if ty is float:<EOL><INDENT>return FLOAT<EOL><DEDENT>if guessed_type:<EOL><INDENT>return STRING<EOL><DEDENT>if __debug__:<EOL><INDENT>try:<EOL><INDENT>if issubclass(ty, ParamType):<EOL><INDENT>raise AssertionError('<STR_LIT>'<EOL>'<STR_LIT>' % ty)<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return FuncParamType(ty)<EOL>

Converts a callable or python ty into the most appropriate param
    ty.


Returns the metavar default for this param if it provides one.


Optionally might return extra information about a missing
        parameter.

        .. versionadded:: 2.0


return value<EOL>

Converts the value.  This is not invoked for values that are
        `None` (the missing value).


return (rv or '<STR_LIT>').split(self.envvar_list_splitter)<EOL>

Given a value from an environment variable this splits it up
        into small chunks depending on the defined envvar list splitter.

        If the splitter is set to `None`, which means that whitespace splits,
        then leading and trailing whitespace is ignored.  Otherwise, leading
        and trailing splitters usually lead to empty items being included.


def fail(self, message, param=None, ctx=None):

raise BadParameter(message, ctx=ctx, param=param)<EOL>

Helper method to fail with an invalid value message.


if PY2:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>import locale<EOL>fs_enc = codecs.lookup(locale.getpreferredencoding()).name<EOL><DEDENT>except Exception:<EOL><INDENT>fs_enc = '<STR_LIT:ascii>'<EOL><DEDENT>if fs_enc != '<STR_LIT:ascii>':<EOL><INDENT>return<EOL><DEDENT>extra = '<STR_LIT>'<EOL>if os.name == '<STR_LIT>':<EOL><INDENT>import subprocess<EOL>rv = subprocess.Popen(['<STR_LIT>', '<STR_LIT>'], stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE).communicate()[<NUM_LIT:0>]<EOL>good_locales = set()<EOL>has_c_utf8 = False<EOL>if isinstance(rv, bytes):<EOL><INDENT>rv = rv.decode('<STR_LIT:ascii>', '<STR_LIT:replace>')<EOL><DEDENT>for line in rv.splitlines():<EOL><INDENT>locale = line.strip()<EOL>if locale.lower().endswith(('<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>good_locales.add(locale)<EOL>if locale.lower() in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>has_c_utf8 = True<EOL><DEDENT><DEDENT><DEDENT>extra += '<STR_LIT>'<EOL>if not good_locales:<EOL><INDENT>extra += (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>elif has_c_utf8:<EOL><INDENT>extra += (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>else:<EOL><INDENT>extra += (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>) % '<STR_LIT:U+002CU+0020>'.join(sorted(good_locales))<EOL><DEDENT>bad_locale = None<EOL>for locale in os.environ.get('<STR_LIT>'), os.environ.get('<STR_LIT>'):<EOL><INDENT>if locale and locale.lower().endswith(('<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>bad_locale = locale<EOL><DEDENT>if locale is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if bad_locale is not None:<EOL><INDENT>extra += (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>) % bad_locale<EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' + extra)<EOL>

Ensures that the environment is good for unicode on Python 3.


def prompt(text, default=None, hide_input=False,<EOL>confirmation_prompt=False, type=None,<EOL>value_proc=None, prompt_suffix='<STR_LIT>',<EOL>show_default=True, err=False):

result = None<EOL>def prompt_func(text):<EOL><INDENT>f = hide_input and hidden_prompt_func or visible_prompt_func<EOL>try:<EOL><INDENT>echo(text, nl=False, err=err)<EOL>return f('<STR_LIT>')<EOL><DEDENT>except (KeyboardInterrupt, EOFError):<EOL><INDENT>if hide_input:<EOL><INDENT>echo(None, err=err)<EOL><DEDENT>raise Abort()<EOL><DEDENT><DEDENT>if value_proc is None:<EOL><INDENT>value_proc = convert_type(type, default)<EOL><DEDENT>prompt = _build_prompt(text, prompt_suffix, show_default, default)<EOL>while <NUM_LIT:1>:<EOL><INDENT>while <NUM_LIT:1>:<EOL><INDENT>value = prompt_func(prompt)<EOL>if value:<EOL><INDENT>break<EOL><DEDENT>elif default is not None:<EOL><INDENT>return default<EOL><DEDENT><DEDENT>try:<EOL><INDENT>result = value_proc(value)<EOL><DEDENT>except UsageError as e:<EOL><INDENT>echo('<STR_LIT>' % e.message, err=err)<EOL>continue<EOL><DEDENT>if not confirmation_prompt:<EOL><INDENT>return result<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>value2 = prompt_func('<STR_LIT>')<EOL>if value2:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if value == value2:<EOL><INDENT>return result<EOL><DEDENT>echo('<STR_LIT>', err=err)<EOL><DEDENT>

Prompts a user for input.  This is a convenience function that can
    be used to prompt a user for input later.

    If the user aborts the input by sending a interrupt signal, this
    function will catch it and raise a :exc:`Abort` exception.

    .. versionadded:: 6.0
       Added unicode support for cmd.exe on Windows.

    .. versionadded:: 4.0
       Added the `err` parameter.

    :param text: the text to show for the prompt.
    :param default: the default value to use if no input happens.  If this
                    is not given it will prompt until it's aborted.
    :param hide_input: if this is set to true then the input value will
                       be hidden.
    :param confirmation_prompt: asks for confirmation for the value.
    :param type: the type to use to check the value against.
    :param value_proc: if this parameter is provided it's a function that
                       is invoked instead of the type conversion to
                       convert a value.
    :param prompt_suffix: a suffix that should be added to the prompt.
    :param show_default: shows or hides the default value in the prompt.
    :param err: if set to true the file defaults to ``stderr`` instead of
                ``stdout``, the same as with echo.


def confirm(text, default=False, abort=False, prompt_suffix='<STR_LIT>',<EOL>show_default=True, err=False):

prompt = _build_prompt(text, prompt_suffix, show_default,<EOL>default and '<STR_LIT>' or '<STR_LIT>')<EOL>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>echo(prompt, nl=False, err=err)<EOL>value = visible_prompt_func('<STR_LIT>').lower().strip()<EOL><DEDENT>except (KeyboardInterrupt, EOFError):<EOL><INDENT>raise Abort()<EOL><DEDENT>if value in ('<STR_LIT:y>', '<STR_LIT:yes>'):<EOL><INDENT>rv = True<EOL><DEDENT>elif value in ('<STR_LIT:n>', '<STR_LIT>'):<EOL><INDENT>rv = False<EOL><DEDENT>elif value == '<STR_LIT>':<EOL><INDENT>rv = default<EOL><DEDENT>else:<EOL><INDENT>echo('<STR_LIT>', err=err)<EOL>continue<EOL><DEDENT>break<EOL><DEDENT>if abort and not rv:<EOL><INDENT>raise Abort()<EOL><DEDENT>return rv<EOL>

Prompts for confirmation (yes/no question).

    If the user aborts the input by sending a interrupt signal this
    function will catch it and raise a :exc:`Abort` exception.

    .. versionadded:: 4.0
       Added the `err` parameter.

    :param text: the question to ask.
    :param default: the default for the prompt.
    :param abort: if this is set to `True` a negative answer aborts the
                  exception by raising :exc:`Abort`.
    :param prompt_suffix: a suffix that should be added to the prompt.
    :param show_default: shows or hides the default value in the prompt.
    :param err: if set to true the file defaults to ``stderr`` instead of
                ``stdout``, the same as with echo.


<EOL>if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:3>):<EOL><INDENT>import shutil<EOL>shutil_get_terminal_size = getattr(shutil, '<STR_LIT>', None)<EOL>if shutil_get_terminal_size:<EOL><INDENT>sz = shutil_get_terminal_size()<EOL>return sz.columns, sz.lines<EOL><DEDENT><DEDENT>if get_winterm_size is not None:<EOL><INDENT>return get_winterm_size()<EOL><DEDENT>def ioctl_gwinsz(fd):<EOL><INDENT>try:<EOL><INDENT>import fcntl<EOL>import termios<EOL>cr = struct.unpack(<EOL>'<STR_LIT>', fcntl.ioctl(fd, termios.TIOCGWINSZ, '<STR_LIT>'))<EOL><DEDENT>except Exception:<EOL><INDENT>return<EOL><DEDENT>return cr<EOL><DEDENT>cr = ioctl_gwinsz(<NUM_LIT:0>) or ioctl_gwinsz(<NUM_LIT:1>) or ioctl_gwinsz(<NUM_LIT:2>)<EOL>if not cr:<EOL><INDENT>try:<EOL><INDENT>fd = os.open(os.ctermid(), os.O_RDONLY)<EOL>try:<EOL><INDENT>cr = ioctl_gwinsz(fd)<EOL><DEDENT>finally:<EOL><INDENT>os.close(fd)<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not cr or not cr[<NUM_LIT:0>] or not cr[<NUM_LIT:1>]:<EOL><INDENT>cr = (os.environ.get('<STR_LIT>', <NUM_LIT>),<EOL>os.environ.get('<STR_LIT>', DEFAULT_COLUMNS))<EOL><DEDENT>return int(cr[<NUM_LIT:1>]), int(cr[<NUM_LIT:0>])<EOL>

Returns the current size of the terminal as tuple in the form
    ``(width, height)`` in columns and rows.


color = resolve_color_default(color)<EOL>if not isinstance(text, string_types):<EOL><INDENT>text = text_type(text)<EOL><DEDENT>from ._termui_impl import pager<EOL>return pager(text + '<STR_LIT:\n>', color)<EOL>

This function takes a text and shows it via an environment specific
    pager on stdout.

    .. versionchanged:: 3.0
       Added the `color` flag.

    :param text: the text to page.
    :param color: controls if the pager supports ANSI colors or not.  The
                  default is autodetection.


def progressbar(iterable=None, length=None, label=None, show_eta=True,<EOL>show_percent=None, show_pos=False,<EOL>item_show_func=None, fill_char='<STR_LIT:#>', empty_char='<STR_LIT:->',<EOL>bar_template='<STR_LIT>',<EOL>info_sep='<STR_LIT:U+0020>', width=<NUM_LIT>, file=None, color=None):

from ._termui_impl import ProgressBar<EOL>color = resolve_color_default(color)<EOL>return ProgressBar(iterable=iterable, length=length, show_eta=show_eta,<EOL>show_percent=show_percent, show_pos=show_pos,<EOL>item_show_func=item_show_func, fill_char=fill_char,<EOL>empty_char=empty_char, bar_template=bar_template,<EOL>info_sep=info_sep, file=file, label=label,<EOL>width=width, color=color)<EOL>

This function creates an iterable context manager that can be used
    to iterate over something while showing a progress bar.  It will
    either iterate over the `iterable` or `length` items (that are counted
    up).  While iteration happens, this function will print a rendered
    progress bar to the given `file` (defaults to stdout) and will attempt
    to calculate remaining time and more.  By default, this progress bar
    will not be rendered if the file is not a terminal.

    The context manager creates the progress bar.  When the context
    manager is entered the progress bar is already displayed.  With every
    iteration over the progress bar, the iterable passed to the bar is
    advanced and the bar is updated.  When the context manager exits,
    a newline is printed and the progress bar is finalized on screen.

    No printing must happen or the progress bar will be unintentionally
    destroyed.

    Example usage::

        with progressbar(items) as bar:
            for item in bar:
                do_something_with(item)

    Alternatively, if no iterable is specified, one can manually update the
    progress bar through the `update()` method instead of directly
    iterating over the progress bar.  The update method accepts the number
    of steps to increment the bar with::

        with progressbar(length=chunks.total_bytes) as bar:
            for chunk in chunks:
                process_chunk(chunk)
                bar.update(chunks.bytes)

    .. versionadded:: 2.0

    .. versionadded:: 4.0
       Added the `color` parameter.  Added a `update` method to the
       progressbar object.

    :param iterable: an iterable to iterate over.  If not provided the length
                     is required.
    :param length: the number of items to iterate over.  By default the
                   progressbar will attempt to ask the iterator about its
                   length, which might or might not work.  If an iterable is
                   also provided this parameter can be used to override the
                   length.  If an iterable is not provided the progress bar
                   will iterate over a range of that length.
    :param label: the label to show next to the progress bar.
    :param show_eta: enables or disables the estimated time display.  This is
                     automatically disabled if the length cannot be
                     determined.
    :param show_percent: enables or disables the percentage display.  The
                         default is `True` if the iterable has a length or
                         `False` if not.
    :param show_pos: enables or disables the absolute position display.  The
                     default is `False`.
    :param item_show_func: a function called with the current item which
                           can return a string to show the current item
                           next to the progress bar.  Note that the current
                           item can be `None`!
    :param fill_char: the character to use to show the filled part of the
                      progress bar.
    :param empty_char: the character to use to show the non-filled part of
                       the progress bar.
    :param bar_template: the format string to use as template for the bar.
                         The parameters in it are ``label`` for the label,
                         ``bar`` for the progress bar and ``info`` for the
                         info section.
    :param info_sep: the separator between multiple info items (eta etc.)
    :param width: the width of the progress bar in characters, 0 means full
                  terminal width
    :param file: the file to write to.  If this is not a terminal then
                 only the label is printed.
    :param color: controls if the terminal supports ANSI colors or not.  The
                  default is autodetection.  This is only needed if ANSI
                  codes are included anywhere in the progress bar output
                  which is not the case by default.


if not isatty(sys.stdout):<EOL><INDENT>return<EOL><DEDENT>if WIN:<EOL><INDENT>os.system('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>sys.stdout.write('<STR_LIT>')<EOL><DEDENT>

Clears the terminal screen.  This will have the effect of clearing
    the whole visible space of the terminal and moving the cursor to the
    top left.  This does not do anything if not connected to a terminal.

    .. versionadded:: 2.0


def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,<EOL>blink=None, reverse=None, reset=True):

bits = []<EOL>if fg:<EOL><INDENT>try:<EOL><INDENT>bits.append('<STR_LIT>' % (_ansi_colors.index(fg) + <NUM_LIT:30>))<EOL><DEDENT>except ValueError:<EOL><INDENT>raise TypeError('<STR_LIT>' % fg)<EOL><DEDENT><DEDENT>if bg:<EOL><INDENT>try:<EOL><INDENT>bits.append('<STR_LIT>' % (_ansi_colors.index(bg) + <NUM_LIT>))<EOL><DEDENT>except ValueError:<EOL><INDENT>raise TypeError('<STR_LIT>' % bg)<EOL><DEDENT><DEDENT>if bold is not None:<EOL><INDENT>bits.append('<STR_LIT>' % (<NUM_LIT:1> if bold else <NUM_LIT>))<EOL><DEDENT>if dim is not None:<EOL><INDENT>bits.append('<STR_LIT>' % (<NUM_LIT:2> if dim else <NUM_LIT>))<EOL><DEDENT>if underline is not None:<EOL><INDENT>bits.append('<STR_LIT>' % (<NUM_LIT:4> if underline else <NUM_LIT>))<EOL><DEDENT>if blink is not None:<EOL><INDENT>bits.append('<STR_LIT>' % (<NUM_LIT:5> if blink else <NUM_LIT>))<EOL><DEDENT>if reverse is not None:<EOL><INDENT>bits.append('<STR_LIT>' % (<NUM_LIT:7> if reverse else <NUM_LIT>))<EOL><DEDENT>bits.append(text)<EOL>if reset:<EOL><INDENT>bits.append(_ansi_reset_all)<EOL><DEDENT>return '<STR_LIT>'.join(bits)<EOL>

Styles a text with ANSI styles and returns the new string.  By
    default the styling is self contained which means that at the end
    of the string a reset code is issued.  This can be prevented by
    passing ``reset=False``.

    Examples::

        click.echo(click.style('Hello World!', fg='green'))
        click.echo(click.style('ATTENTION!', blink=True))
        click.echo(click.style('Some things', reverse=True, fg='cyan'))

    Supported color names:

    * ``black`` (might be a gray)
    * ``red``
    * ``green``
    * ``yellow`` (might be an orange)
    * ``blue``
    * ``magenta``
    * ``cyan``
    * ``white`` (might be light gray)
    * ``reset`` (reset the color code only)

    .. versionadded:: 2.0

    :param text: the string to style with ansi codes.
    :param fg: if provided this will become the foreground color.
    :param bg: if provided this will become the background color.
    :param bold: if provided this will enable or disable bold mode.
    :param dim: if provided this will enable or disable dim mode.  This is
                badly supported.
    :param underline: if provided this will enable or disable underline.
    :param blink: if provided this will enable or disable blinking.
    :param reverse: if provided this will enable or disable inverse
                    rendering (foreground becomes background and the
                    other way round).
    :param reset: by default a reset-all code is added at the end of the
                  string which means that styles do not carry over.  This
                  can be disabled to compose styles.


return strip_ansi(text)<EOL>

Removes ANSI styling information from a string.  Usually it's not
    necessary to use this function as Click's echo function will
    automatically remove styling if necessary.

    .. versionadded:: 2.0

    :param text: the text to remove style information from.


def secho(text, file=None, nl=True, err=False, color=None, **styles):

return echo(style(text, **styles), file=file, nl=nl, err=err, color=color)<EOL>

This function combines :func:`echo` and :func:`style` into one
    call.  As such the following two calls are the same::

        click.secho('Hello World!', fg='green')
        click.echo(click.style('Hello World!', fg='green'))

    All keyword arguments are forwarded to the underlying functions
    depending on which one they go with.

    .. versionadded:: 2.0


def edit(text=None, editor=None, env=None, require_save=True,<EOL>extension='<STR_LIT>', filename=None):

from ._termui_impl import Editor<EOL>editor = Editor(editor=editor, env=env, require_save=require_save,<EOL>extension=extension)<EOL>if filename is None:<EOL><INDENT>return editor.edit(text)<EOL><DEDENT>editor.edit_file(filename)<EOL>

r"""Edits the given text in the defined editor.  If an editor is given
    (should be the full path to the executable but the regular operating
    system search path is used for finding the executable) it overrides
    the detected editor.  Optionally, some environment variables can be
    used.  If the editor is closed without changes, `None` is returned.  In
    case a file is edited directly the return value is always `None` and
    `require_save` and `extension` are ignored.

    If the editor cannot be opened a :exc:`UsageError` is raised.

    Note for Windows: to simplify cross-platform usage, the newlines are
    automatically converted from POSIX to Windows and vice versa.  As such,
    the message here will have ``\n`` as newline markers.

    :param text: the text to edit.
    :param editor: optionally the editor to use.  Defaults to automatic
                   detection.
    :param env: environment variables to forward to the editor.
    :param require_save: if this is true, then not saving in the editor
                         will make the return value become `None`.
    :param extension: the extension to tell the editor about.  This defaults
                      to `.txt` but changing this might change syntax
                      highlighting.
    :param filename: if provided it will edit this file instead of the
                     provided text contents.  It will not use a temporary
                     file as an indirection in that case.


def launch(url, wait=False, locate=False):

from ._termui_impl import open_url<EOL>return open_url(url, wait=wait, locate=locate)<EOL>

This function launches the given URL (or filename) in the default
    viewer application for this file type.  If this is an executable, it
    might launch the executable in a new session.  The return value is
    the exit code of the launched application.  Usually, ``0`` indicates
    success.

    Examples::

        click.launch('http://click.pocoo.org/')
        click.launch('/my/downloaded/file', locate=True)

    .. versionadded:: 2.0

    :param url: URL or filename of the thing to launch.
    :param wait: waits for the program to stop.
    :param locate: if this is set to `True` then instead of launching the
                   application associated with the URL it will attempt to
                   launch a file manager with the file located.  This
                   might have weird effects if the URL does not point to
                   the filesystem.


f = _getchar<EOL>if f is None:<EOL><INDENT>from ._termui_impl import getchar as f<EOL><DEDENT>return f(echo)<EOL>

Fetches a single character from the terminal and returns it.  This
    will always return a unicode character and under certain rare
    circumstances this might return more than one character.  The
    situations which more than one character is returned is when for
    whatever reason multiple characters end up in the terminal buffer or
    standard input was not actually a terminal.

    Note that this will always read from the terminal, even if something
    is piped into the standard input.

    .. versionadded:: 2.0

    :param echo: if set to `True`, the character read will also show up on
                 the terminal.  The default is to not show it.


if not isatty(sys.stdin) or not isatty(sys.stdout):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>if info:<EOL><INDENT>echo(info, nl=False, err=err)<EOL><DEDENT>try:<EOL><INDENT>getchar()<EOL><DEDENT>except (KeyboardInterrupt, EOFError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if info:<EOL><INDENT>echo(err=err)<EOL><DEDENT><DEDENT>

This command stops execution and waits for the user to press any
    key to continue.  This is similar to the Windows batch "pause"
    command.  If the program is not run through a terminal, this command
    will instead do nothing.

    .. versionadded:: 2.0

    .. versionadded:: 4.0
       Added the `err` parameter.

    :param info: the info string to print before pausing.
    :param err: if set to message goes to ``stderr`` instead of
                ``stdout``, the same as with echo.


def _bashcomplete(cmd, prog_name, complete_var=None):

if complete_var is None:<EOL><INDENT>complete_var = '<STR_LIT>' % (prog_name.replace('<STR_LIT:->', '<STR_LIT:_>')).upper()<EOL><DEDENT>complete_instr = os.environ.get(complete_var)<EOL>if not complete_instr:<EOL><INDENT>return<EOL><DEDENT>from ._bashcomplete import bashcomplete<EOL>if bashcomplete(cmd, prog_name, complete_var, complete_instr):<EOL><INDENT>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>

Internal handler for the bash completion support.


try:<EOL><INDENT>yield<EOL><DEDENT>except BadParameter as e:<EOL><INDENT>if e.ctx is None:<EOL><INDENT>e.ctx = ctx<EOL><DEDENT>if param is not None and e.param is None:<EOL><INDENT>e.param = param<EOL><DEDENT>raise<EOL><DEDENT>except UsageError as e:<EOL><INDENT>if e.ctx is None:<EOL><INDENT>e.ctx = ctx<EOL><DEDENT>raise<EOL><DEDENT>

Context manager that attaches extra information to exceptions that
    fly.


def sort_key(item):<EOL><INDENT>try:<EOL><INDENT>idx = invocation_order.index(item)<EOL><DEDENT>except ValueError:<EOL><INDENT>idx = float('<STR_LIT>')<EOL><DEDENT>return (not item.is_eager, idx)<EOL><DEDENT>return sorted(declaration_order, key=sort_key)<EOL>

Given a sequence of parameters in the order as should be considered
    for processing and an iterable of parameters that exist, this returns
    a list in the correct order as they should be processed.


if not cleanup:<EOL><INDENT>self._depth += <NUM_LIT:1><EOL><DEDENT>try:<EOL><INDENT>with self as rv:<EOL><INDENT>yield rv<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if not cleanup:<EOL><INDENT>self._depth -= <NUM_LIT:1><EOL><DEDENT><DEDENT>

This helper method can be used with the context object to promote
        it to the current thread local (see :func:`get_current_context`).
        The default behavior of this is to invoke the cleanup functions which
        can be disabled by setting `cleanup` to `False`.  The cleanup
        functions are typically used for things such as closing file handles.

        If the cleanup is intended the context object can also be directly
        used as a context manager.

        Example usage::

            with ctx.scope():
                assert get_current_context() is ctx

        This is equivalent::

            with ctx:
                assert get_current_context() is ctx

        .. versionadded:: 5.0

        :param cleanup: controls if the cleanup functions should be run or
                        not.  The default is to run these functions.  In
                        some situations the context only wants to be
                        temporarily pushed in which case this can be disabled.
                        Nested pushes automatically defer the cleanup.


return self._meta<EOL>

This is a dictionary which is shared with all the contexts
        that are nested.  It exists so that click utiltiies can store some
        state here if they need to.  It is however the responsibility of
        that code to manage this dictionary well.

        The keys are supposed to be unique dotted strings.  For instance
        module paths are a good choice for it.  What is stored in there is
        irrelevant for the operation of click.  However what is important is
        that code that places data here adheres to the general semantics of
        the system.

        Example usage::

            LANG_KEY = __name__ + '.lang'

            def set_language(value):
                ctx = get_current_context()
                ctx.meta[LANG_KEY] = value

            def get_language():
                return get_current_context().meta.get(LANG_KEY, 'en_US')

        .. versionadded:: 5.0


return HelpFormatter(width=self.terminal_width,<EOL>max_width=self.max_content_width)<EOL>

Creates the formatter for the help and usage output.


self._close_callbacks.append(f)<EOL>return f<EOL>

This decorator remembers a function as callback that should be
        executed when the context tears down.  This is most useful to bind
        resource handling to the script execution.  For instance, file objects
        opened by the :class:`File` type will register their close callbacks
        here.

        :param f: the function to execute on teardown.


for cb in self._close_callbacks:<EOL><INDENT>cb()<EOL><DEDENT>self._close_callbacks = []<EOL>


rv = '<STR_LIT>'<EOL>if self.info_name is not None:<EOL><INDENT>rv = self.info_name<EOL><DEDENT>if self.parent is not None:<EOL><INDENT>rv = self.parent.command_path + '<STR_LIT:U+0020>' + rv<EOL><DEDENT>return rv.lstrip()<EOL>

The computed command path.  This is used for the ``usage``
        information on the help page.  It's automatically created by
        combining the info names of the chain of contexts to the root.


node = self<EOL>while node.parent is not None:<EOL><INDENT>node = node.parent<EOL><DEDENT>return node<EOL>


node = self<EOL>while node is not None:<EOL><INDENT>if isinstance(node.obj, object_type):<EOL><INDENT>return node.obj<EOL><DEDENT>node = node.parent<EOL><DEDENT>

Finds the closest object of a given type.


rv = self.find_object(object_type)<EOL>if rv is None:<EOL><INDENT>self.obj = rv = object_type()<EOL><DEDENT>return rv<EOL>

Like :meth:`find_object` but sets the innermost object to a
        new instance of `object_type` if it does not exist.


if self.default_map is not None:<EOL><INDENT>rv = self.default_map.get(name)<EOL>if callable(rv):<EOL><INDENT>rv = rv()<EOL><DEDENT>return rv<EOL><DEDENT>

Looks up the default for a parameter name.  This by default
        looks into the :attr:`default_map` if available.


raise UsageError(message, self)<EOL>

Aborts the execution of the program with a specific error
        message.

        :param message: the error message to fail with.


raise Abort()<EOL>


sys.exit(code)<EOL>

Exits the application with a given exit code.


return self.command.get_usage(self)<EOL>

Helper method to get formatted usage string for the current
        context and command.


return self.command.get_help(self)<EOL>

Helper method to get formatted help page for the current
        context and command.


self, callback = args[:<NUM_LIT:2>]<EOL>ctx = self<EOL>if isinstance(callback, Command):<EOL><INDENT>other_cmd = callback<EOL>callback = other_cmd.callback<EOL>ctx = Context(other_cmd, info_name=other_cmd.name, parent=self)<EOL>if callback is None:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>for param in other_cmd.params:<EOL><INDENT>if param.name not in kwargs and param.expose_value:<EOL><INDENT>kwargs[param.name] = param.get_default(ctx)<EOL><DEDENT><DEDENT><DEDENT>args = args[<NUM_LIT:2>:]<EOL>with augment_usage_errors(self):<EOL><INDENT>with ctx:<EOL><INDENT>return callback(*args, **kwargs)<EOL><DEDENT><DEDENT>

Invokes a command callback in exactly the way it expects.  There
        are two ways to invoke this method:

        1.  the first argument can be a callback and all other arguments and
            keyword arguments are forwarded directly to the function.
        2.  the first argument is a click command object.  In that case all
            arguments are forwarded as well but proper click parameters
            (options and click arguments) must be keyword arguments and Click
            will fill in defaults.

        Note that before Click 3.2 keyword arguments were not properly filled
        in against the intention of this code and no context was created.  For
        more information about this change and why it was done in a bugfix
        release see :ref:`upgrade-to-3.2`.


self, cmd = args[:<NUM_LIT:2>]<EOL>if not isinstance(cmd, Command):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>for param in self.params:<EOL><INDENT>if param not in kwargs:<EOL><INDENT>kwargs[param] = self.params[param]<EOL><DEDENT><DEDENT>return self.invoke(cmd, **kwargs)<EOL>

Similar to :meth:`invoke` but fills in default keyword
        arguments from the current context if the other command expects
        it.  This cannot invoke callbacks directly, only other commands.


def make_context(self, info_name, args, parent=None, **extra):

for key, value in iteritems(self.context_settings):<EOL><INDENT>if key not in extra:<EOL><INDENT>extra[key] = value<EOL><DEDENT><DEDENT>ctx = Context(self, info_name=info_name, parent=parent, **extra)<EOL>with ctx.scope(cleanup=False):<EOL><INDENT>self.parse_args(ctx, args)<EOL><DEDENT>return ctx<EOL>

This function when given an info name and arguments will kick
        off the parsing and create a new :class:`Context`.  It does not
        invoke the actual command callback though.

        :param info_name: the info name for this invokation.  Generally this
                          is the most descriptive name for the script or
                          command.  For the toplevel script it's usually
                          the name of the script, for commands below it it's
                          the name of the script.
        :param args: the arguments to parse as list of strings.
        :param parent: the parent context if available.
        :param extra: extra keyword arguments forwarded to the context
                      constructor.


raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>

Given a context and a list of arguments this creates the parser
        and parses the arguments, then modifies the context as necessary.
        This is automatically invoked by :meth:`make_context`.


raise NotImplementedError('<STR_LIT>')<EOL>

Given a context, this invokes the command.  The default
        implementation is raising a not implemented error.


def main(self, args=None, prog_name=None, complete_var=None,<EOL>standalone_mode=True, **extra):

<EOL>if not PY2:<EOL><INDENT>_verify_python3_env()<EOL><DEDENT>else:<EOL><INDENT>_check_for_unicode_literals()<EOL><DEDENT>if args is None:<EOL><INDENT>args = get_os_args()<EOL><DEDENT>else:<EOL><INDENT>args = list(args)<EOL><DEDENT>if prog_name is None:<EOL><INDENT>prog_name = make_str(os.path.basename(<EOL>sys.argv and sys.argv[<NUM_LIT:0>] or __file__))<EOL><DEDENT>_bashcomplete(self, prog_name, complete_var)<EOL>try:<EOL><INDENT>try:<EOL><INDENT>with self.make_context(prog_name, args, **extra) as ctx:<EOL><INDENT>rv = self.invoke(ctx)<EOL>if not standalone_mode:<EOL><INDENT>return rv<EOL><DEDENT>ctx.exit()<EOL><DEDENT><DEDENT>except (EOFError, KeyboardInterrupt):<EOL><INDENT>echo(file=sys.stderr)<EOL>raise Abort()<EOL><DEDENT>except ClickException as e:<EOL><INDENT>if not standalone_mode:<EOL><INDENT>raise<EOL><DEDENT>e.show()<EOL>sys.exit(e.exit_code)<EOL><DEDENT>except IOError as e:<EOL><INDENT>if e.errno == errno.EPIPE:<EOL><INDENT>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>except Abort:<EOL><INDENT>if not standalone_mode:<EOL><INDENT>raise<EOL><DEDENT>echo('<STR_LIT>', file=sys.stderr)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>

This is the way to invoke a script with all the bells and
        whistles as a command line application.  This will always terminate
        the application after a call.  If this is not wanted, ``SystemExit``
        needs to be caught.

        This method is also available by directly calling the instance of
        a :class:`Command`.

        .. versionadded:: 3.0
           Added the `standalone_mode` flag to control the standalone mode.

        :param args: the arguments that should be used for parsing.  If not
                     provided, ``sys.argv[1:]`` is used.
        :param prog_name: the program name that should be used.  By default
                          the program name is constructed by taking the file
                          name from ``sys.argv[0]``.
        :param complete_var: the environment variable that controls the
                             bash completion support.  The default is
                             ``"_<prog_name>_COMPLETE"`` with prog name in
                             uppercase.
        :param standalone_mode: the default behavior is to invoke the script
                                in standalone mode.  Click will then
                                handle exceptions and convert them into
                                error messages and the function will never
                                return but shut down the interpreter.  If
                                this is set to `False` they will be
                                propagated to the caller and the return
                                value of this function is the return value
                                of :meth:`invoke`.
        :param extra: extra keyword arguments are forwarded to the context
                      constructor.  See :class:`Context` for more information.


return self.main(*args, **kwargs)<EOL>


pieces = self.collect_usage_pieces(ctx)<EOL>formatter.write_usage(ctx.command_path, '<STR_LIT:U+0020>'.join(pieces))<EOL>

Writes the usage line into the formatter.


rv = [self.options_metavar]<EOL>for param in self.get_params(ctx):<EOL><INDENT>rv.extend(param.get_usage_pieces(ctx))<EOL><DEDENT>return rv<EOL>

Returns all the pieces that go into the usage line and returns
        it as a list of strings.


all_names = set(ctx.help_option_names)<EOL>for param in self.params:<EOL><INDENT>all_names.difference_update(param.opts)<EOL>all_names.difference_update(param.secondary_opts)<EOL><DEDENT>return all_names<EOL>


help_options = self.get_help_option_names(ctx)<EOL>if not help_options or not self.add_help_option:<EOL><INDENT>return<EOL><DEDENT>def show_help(ctx, param, value):<EOL><INDENT>if value and not ctx.resilient_parsing:<EOL><INDENT>echo(ctx.get_help(), color=ctx.color)<EOL>ctx.exit()<EOL><DEDENT><DEDENT>return Option(help_options, is_flag=True,<EOL>is_eager=True, expose_value=False,<EOL>callback=show_help,<EOL>help='<STR_LIT>')<EOL>


parser = OptionParser(ctx)<EOL>parser.allow_interspersed_args = ctx.allow_interspersed_args<EOL>parser.ignore_unknown_options = ctx.ignore_unknown_options<EOL>for param in self.get_params(ctx):<EOL><INDENT>param.add_to_parser(parser, ctx)<EOL><DEDENT>return parser<EOL>

Creates the underlying option parser for this command.


formatter = ctx.make_formatter()<EOL>self.format_help(ctx, formatter)<EOL>return formatter.getvalue().rstrip('<STR_LIT:\n>')<EOL>

Formats the help into a string and returns it.  This creates a
        formatter and will call into the following formatting methods:


self.format_usage(ctx, formatter)<EOL>self.format_help_text(ctx, formatter)<EOL>self.format_options(ctx, formatter)<EOL>self.format_epilog(ctx, formatter)<EOL>

Writes the help into the formatter if it exists.

        This calls into the following methods:

        -   :meth:`format_usage`
        -   :meth:`format_help_text`
        -   :meth:`format_options`
        -   :meth:`format_epilog`


def format_help_text(self, ctx, formatter):

if self.help:<EOL><INDENT>formatter.write_paragraph()<EOL>with formatter.indentation():<EOL><INDENT>formatter.write_text(self.help)<EOL><DEDENT><DEDENT>

Writes the help text to the formatter if it exists.


def format_options(self, ctx, formatter):

opts = []<EOL>for param in self.get_params(ctx):<EOL><INDENT>rv = param.get_help_record(ctx)<EOL>if rv is not None:<EOL><INDENT>opts.append(rv)<EOL><DEDENT><DEDENT>if opts:<EOL><INDENT>with formatter.section('<STR_LIT>'):<EOL><INDENT>formatter.write_dl(opts)<EOL><DEDENT><DEDENT>

Writes all the options into the formatter if they exist.


def format_epilog(self, ctx, formatter):

if self.epilog:<EOL><INDENT>formatter.write_paragraph()<EOL>with formatter.indentation():<EOL><INDENT>formatter.write_text(self.epilog)<EOL><DEDENT><DEDENT>

Writes the epilog into the formatter if it exists.


if self.callback is not None:<EOL><INDENT>return ctx.invoke(self.callback, **ctx.params)<EOL><DEDENT>

Given a context, this invokes the attached callback (if it exists)
        in the right way.


def decorator(f):<EOL><INDENT>old_callback = self.result_callback<EOL>if old_callback is None or replace:<EOL><INDENT>self.result_callback = f<EOL>return f<EOL><DEDENT>def function(__value, *args, **kwargs):<EOL><INDENT>return f(old_callback(__value, *args, **kwargs),<EOL>*args, **kwargs)<EOL><DEDENT>self.result_callback = rv = update_wrapper(function, f)<EOL>return rv<EOL><DEDENT>return decorator<EOL>

Adds a result callback to the chain command.  By default if a
        result callback is already registered this will chain them but
        this can be disabled with the `replace` parameter.  The result
        callback is invoked with the return value of the subcommand
        (or the list of return values from all subcommands if chaining
        is enabled) as well as the parameters as they would be passed
        to the main callback.

        Example::

            @click.group()
            @click.option('-i', '--input', default=23)
            def cli(input):
                return 42

            @cli.resultcallback()
            def process_result(result, input):
                return result + input

        .. versionadded:: 3.0

        :param replace: if set to `True` an already existing result
                        callback will be removed.


def format_commands(self, ctx, formatter):

rows = []<EOL>for subcommand in self.list_commands(ctx):<EOL><INDENT>cmd = self.get_command(ctx, subcommand)<EOL>if cmd is None:<EOL><INDENT>continue<EOL><DEDENT>help = cmd.short_help or '<STR_LIT>'<EOL>rows.append((subcommand, help))<EOL><DEDENT>if rows:<EOL><INDENT>with formatter.section('<STR_LIT>'):<EOL><INDENT>formatter.write_dl(rows)<EOL><DEDENT><DEDENT>

Extra format methods for multi methods that adds all the commands
        after the options.


raise NotImplementedError()<EOL>

Given a context and a command name, this returns a
        :class:`Command` object if it exists or returns `None`.


return []<EOL>

Returns a list of subcommand names in the order they should
        appear.


name = name or cmd.name<EOL>if name is None:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>_check_multicommand(self, name, cmd, register=True)<EOL>self.commands[name] = cmd<EOL>

Registers another :class:`Command` with this group.  If the name
        is not provided, the name of the command is used.


def decorator(f):<EOL><INDENT>cmd = command(*args, **kwargs)(f)<EOL>self.add_command(cmd)<EOL>return cmd<EOL><DEDENT>return decorator<EOL>

A shortcut decorator for declaring and attaching a command to
        the group.  This takes the same arguments as :func:`command` but
        immediately registers the created command with this instance by
        calling into :meth:`add_command`.


def decorator(f):<EOL><INDENT>cmd = group(*args, **kwargs)(f)<EOL>self.add_command(cmd)<EOL>return cmd<EOL><DEDENT>return decorator<EOL>

A shortcut decorator for declaring and attaching a group to
        the group.  This takes the same arguments as :func:`group` but
        immediately registers the created command with this instance by
        calling into :meth:`add_command`.


Adds a new multi command to the chain dispatcher.


return self.name<EOL>

Returns the human readable name of this parameter.  This is the
        same as the name for options, but the metavar for arguments.


<EOL>if callable(self.default):<EOL><INDENT>rv = self.default()<EOL><DEDENT>else:<EOL><INDENT>rv = self.default<EOL><DEDENT>return self.type_cast_value(ctx, rv)<EOL>

Given a context variable this calculates the default value.


if self.type.is_composite:<EOL><INDENT>if self.nargs <= <NUM_LIT:1>:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % self.nargs)<EOL><DEDENT>if self.multiple:<EOL><INDENT>return tuple(self.type(x or (), self, ctx) for x in value or ())<EOL><DEDENT>return self.type(value or (), self, ctx)<EOL><DEDENT>def _convert(value, level):<EOL><INDENT>if level == <NUM_LIT:0>:<EOL><INDENT>return self.type(value, self, ctx)<EOL><DEDENT>return tuple(_convert(x, level - <NUM_LIT:1>) for x in value or ())<EOL><DEDENT>return _convert(value, (self.nargs != <NUM_LIT:1>) + bool(self.multiple))<EOL>

Given a value this runs it properly through the type system.
        This automatically handles things like `nargs` and `multiple` as
        well as composite types.


<EOL>if value is not None:<EOL><INDENT>return self.type_cast_value(ctx, value)<EOL><DEDENT>

Given a value and context this runs the logic to convert the
        value as necessary.


<EOL>default = self.get_default(ctx)<EOL>if self.is_bool_flag:<EOL><INDENT>return confirm(self.prompt, default)<EOL><DEDENT>return prompt(self.prompt, default=default,<EOL>hide_input=self.hide_input,<EOL>confirmation_prompt=self.confirmation_prompt,<EOL>value_proc=lambda x: self.process_value(ctx, x))<EOL>

This is an alternative flow that can be activated in the full
        value processing if a value does not exist.  It will prompt the
        user until a valid value exists and then returns the processed
        value as result.


def wrapper(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return wrapper<EOL>

Wraps a function so that it swallows exceptions.


if isinstance(value, bytes):<EOL><INDENT>try:<EOL><INDENT>return value.decode(get_filesystem_encoding())<EOL><DEDENT>except UnicodeError:<EOL><INDENT>return value.decode('<STR_LIT:utf-8>', '<STR_LIT:replace>')<EOL><DEDENT><DEDENT>return text_type(value)<EOL>


def echo(message=None, file=None, nl=True, err=False, color=None):

if file is None:<EOL><INDENT>if err:<EOL><INDENT>file = _default_text_stderr()<EOL><DEDENT>else:<EOL><INDENT>file = _default_text_stdout()<EOL><DEDENT><DEDENT>if message is not None and not isinstance(message, echo_native_types):<EOL><INDENT>message = text_type(message)<EOL><DEDENT>if nl:<EOL><INDENT>message = message or u'<STR_LIT>'<EOL>if isinstance(message, text_type):<EOL><INDENT>message += u'<STR_LIT:\n>'<EOL><DEDENT>else:<EOL><INDENT>message += b'<STR_LIT:\n>'<EOL><DEDENT><DEDENT>if message and not PY2 and is_bytes(message):<EOL><INDENT>binary_file = _find_binary_writer(file)<EOL>if binary_file is not None:<EOL><INDENT>file.flush()<EOL>binary_file.write(message)<EOL>binary_file.flush()<EOL>return<EOL><DEDENT><DEDENT>if message and not is_bytes(message):<EOL><INDENT>color = resolve_color_default(color)<EOL>if should_strip_ansi(file, color):<EOL><INDENT>message = strip_ansi(message)<EOL><DEDENT>elif WIN:<EOL><INDENT>if auto_wrap_for_ansi is not None:<EOL><INDENT>file = auto_wrap_for_ansi(file)<EOL><DEDENT>elif not color:<EOL><INDENT>message = strip_ansi(message)<EOL><DEDENT><DEDENT><DEDENT>if message:<EOL><INDENT>file.write(message)<EOL><DEDENT>file.flush()<EOL>

Prints a message plus a newline to the given file or stdout.  On
    first sight, this looks like the print function, but it has improved
    support for handling Unicode and binary data that does not fail no
    matter how badly configured the system is.

    Primarily it means that you can print binary data as well as Unicode
    data on both 2.x and 3.x to the given file in the most appropriate way
    possible.  This is a very carefree function as in that it will try its
    best to not fail.  As of Click 6.0 this includes support for unicode
    output on the Windows console.

    In addition to that, if `colorama`_ is installed, the echo function will
    also support clever handling of ANSI codes.  Essentially it will then
    do the following:

    -   add transparent handling of ANSI color codes on Windows.
    -   hide ANSI codes automatically if the destination file is not a
        terminal.

    .. _colorama: http://pypi.python.org/pypi/colorama

    .. versionchanged:: 6.0
       As of Click 6.0 the echo function will properly support unicode
       output on the windows console.  Not that click does not modify
       the interpreter in any way which means that `sys.stdout` or the
       print statement or function will still not provide unicode support.

    .. versionchanged:: 2.0
       Starting with version 2.0 of Click, the echo function will work
       with colorama if it's installed.

    .. versionadded:: 3.0
       The `err` parameter was added.

    .. versionchanged:: 4.0
       Added the `color` flag.

    :param message: the message to print
    :param file: the file to write to (defaults to ``stdout``)
    :param err: if set to true the file defaults to ``stderr`` instead of
                ``stdout``.  This is faster and easier than calling
                :func:`get_text_stderr` yourself.
    :param nl: if set to `True` (the default) a newline is printed afterwards.
    :param color: controls if the terminal supports ANSI colors or not.  The
                  default is autodetection.


opener = binary_streams.get(name)<EOL>if opener is None:<EOL><INDENT>raise TypeError('<STR_LIT>' % name)<EOL><DEDENT>return opener()<EOL>

Returns a system stream for byte processing.  This essentially
    returns the stream from the sys module with the given name but it
    solves some compatibility issues between different Python versions.
    Primarily this function is necessary for getting binary streams on
    Python 3.

    :param name: the name of the stream to open.  Valid names are ``'stdin'``,
                 ``'stdout'`` and ``'stderr'``


def get_text_stream(name, encoding=None, errors='<STR_LIT:strict>'):

opener = text_streams.get(name)<EOL>if opener is None:<EOL><INDENT>raise TypeError('<STR_LIT>' % name)<EOL><DEDENT>return opener(encoding, errors)<EOL>

Returns a system stream for text processing.  This usually returns
    a wrapped stream around a binary stream returned from
    :func:`get_binary_stream` but it also can take shortcuts on Python 3
    for already correctly configured streams.

    :param name: the name of the stream to open.  Valid names are ``'stdin'``,
                 ``'stdout'`` and ``'stderr'``
    :param encoding: overrides the detected default encoding.
    :param errors: overrides the default error mode.


def open_file(filename, mode='<STR_LIT:r>', encoding=None, errors='<STR_LIT:strict>',<EOL>lazy=False, atomic=False):

if lazy:<EOL><INDENT>return LazyFile(filename, mode, encoding, errors, atomic=atomic)<EOL><DEDENT>f, should_close = open_stream(filename, mode, encoding, errors,<EOL>atomic=atomic)<EOL>if not should_close:<EOL><INDENT>f = KeepOpenFile(f)<EOL><DEDENT>return f<EOL>

This is similar to how the :class:`File` works but for manual
    usage.  Files are opened non lazy by default.  This can open regular
    files as well as stdin/stdout if ``'-'`` is passed.

    If stdin/stdout is returned the stream is wrapped so that the context
    manager will not close the stream accidentally.  This makes it possible
    to always use the function like this without having to worry to
    accidentally close a standard stream::

        with open_file(filename) as f:
            ...

    .. versionadded:: 3.0

    :param filename: the name of the file to open (or ``'-'`` for stdin/stdout).
    :param mode: the mode in which to open the file.
    :param encoding: the encoding to use.
    :param errors: the error handling for this file.
    :param lazy: can be flipped to true to open the file lazily.
    :param atomic: in atomic mode writes go into a temporary file and it's
                   moved on close.


<EOL>if PY2 and WIN and _initial_argv_hash == _hash_py_argv():<EOL><INDENT>return _get_windows_argv()<EOL><DEDENT>return sys.argv[<NUM_LIT:1>:]<EOL>

This returns the argument part of sys.argv in the most appropriate
    form for processing.  What this means is that this return value is in
    a format that works for Click to process but does not necessarily
    correspond well to what's actually standard for the interpreter.

    On most environments the return value is ``sys.argv[:1]`` unchanged.
    However if you are on Windows and running Python 2 the return value
    will actually be a list of unicode strings instead because the
    default behavior on that platform otherwise will not be able to
    carry all possible values that sys.argv can have.

    .. versionadded:: 6.0


if shorten:<EOL><INDENT>filename = os.path.basename(filename)<EOL><DEDENT>return filename_to_ui(filename)<EOL>

Formats a filename for user display.  The main purpose of this
    function is to ensure that the filename can be displayed at all.  This
    will decode the filename to unicode if necessary in a way that it will
    not fail.  Optionally, it can shorten the filename to not include the
    full path to the filename.

    :param filename: formats a filename for UI display.  This will also convert
                     the filename into unicode without failing.
    :param shorten: this optionally shortens the filename to strip of the
                    path that leads up to it.


def get_app_dir(app_name, roaming=True, force_posix=False):

if WIN:<EOL><INDENT>key = roaming and '<STR_LIT>' or '<STR_LIT>'<EOL>folder = os.environ.get(key)<EOL>if folder is None:<EOL><INDENT>folder = os.path.expanduser('<STR_LIT>')<EOL><DEDENT>return os.path.join(folder, app_name)<EOL><DEDENT>if force_posix:<EOL><INDENT>return os.path.join(os.path.expanduser('<STR_LIT>' + _posixify(app_name)))<EOL><DEDENT>if sys.platform == '<STR_LIT>':<EOL><INDENT>return os.path.join(os.path.expanduser(<EOL>'<STR_LIT>'), app_name)<EOL><DEDENT>return os.path.join(<EOL>os.environ.get('<STR_LIT>', os.path.expanduser('<STR_LIT>')),<EOL>_posixify(app_name))<EOL>

r"""Returns the config folder for the application.  The default behavior
    is to return whatever is most appropriate for the operating system.

    To give you an idea, for an app called ``"Foo Bar"``, something like
    the following folders could be returned:

    Mac OS X:
      ``~/Library/Application Support/Foo Bar``
    Mac OS X (POSIX):
      ``~/.foo-bar``
    Unix:
      ``~/.config/foo-bar``
    Unix (POSIX):
      ``~/.foo-bar``
    Win XP (roaming):
      ``C:\Documents and Settings\<user>\Local Settings\Application Data\Foo Bar``
    Win XP (not roaming):
      ``C:\Documents and Settings\<user>\Application Data\Foo Bar``
    Win 7 (roaming):
      ``C:\Users\<user>\AppData\Roaming\Foo Bar``
    Win 7 (not roaming):
      ``C:\Users\<user>\AppData\Local\Foo Bar``

    .. versionadded:: 2.0

    :param app_name: the application name.  This should be properly capitalized
                     and can contain whitespace.
    :param roaming: controls if the folder should be roaming or not on Windows.
                    Has no affect otherwise.
    :param force_posix: if this is set to `True` then on any POSIX system the
                        folder will be stored in the home folder with a leading
                        dot instead of the XDG config home or darwin's
                        application support folder.


if self._f is not None:<EOL><INDENT>return self._f<EOL><DEDENT>try:<EOL><INDENT>rv, self.should_close = open_stream(self.name, self.mode,<EOL>self.encoding,<EOL>self.errors,<EOL>atomic=self.atomic)<EOL><DEDENT>except (IOError, OSError) as e:<EOL><INDENT>from .exceptions import FileError<EOL>raise FileError(self.name, hint=get_streerror(e))<EOL><DEDENT>self._f = rv<EOL>return rv<EOL>

Opens the file if it's not yet open.  This call might fail with
        a :exc:`FileError`.  Not handling this error will produce an error
        that Click shows.


if self._f is not None:<EOL><INDENT>self._f.close()<EOL><DEDENT>

Closes the underlying file, no matter what.


if self.should_close:<EOL><INDENT>self.close()<EOL><DEDENT>

This function only closes the file if it was opened by the lazy
        file wrapper.  For instance this will never close stdin.


def new_func(*args, **kwargs):<EOL><INDENT>return f(get_current_context(), *args, **kwargs)<EOL><DEDENT>return update_wrapper(new_func, f)<EOL>

Marks a callback as wanting to receive the current context
    object as first argument.


def new_func(*args, **kwargs):<EOL><INDENT>return f(get_current_context().obj, *args, **kwargs)<EOL><DEDENT>return update_wrapper(new_func, f)<EOL>

Similar to :func:`pass_context`, but only pass the object on the
    context onwards (:attr:`Context.obj`).  This is useful if that object
    represents the state of a nested system.


def decorator(f):<EOL><INDENT>def new_func(*args, **kwargs):<EOL><INDENT>ctx = get_current_context()<EOL>if ensure:<EOL><INDENT>obj = ctx.ensure_object(object_type)<EOL><DEDENT>else:<EOL><INDENT>obj = ctx.find_object(object_type)<EOL><DEDENT>if obj is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>% object_type.__name__)<EOL><DEDENT>return ctx.invoke(f, obj, *args[<NUM_LIT:1>:], **kwargs)<EOL><DEDENT>return update_wrapper(new_func, f)<EOL><DEDENT>return decorator<EOL>

Given an object type this creates a decorator that will work
    similar to :func:`pass_obj` but instead of passing the object of the
    current context, it will find the innermost context of type
    :func:`object_type`.

    This generates a decorator that works roughly like this::

        from functools import update_wrapper

        def decorator(f):
            @pass_context
            def new_func(ctx, *args, **kwargs):
                obj = ctx.find_object(object_type)
                return ctx.invoke(f, obj, *args, **kwargs)
            return update_wrapper(new_func, f)
        return decorator

    :param object_type: the type of the object to pass.
    :param ensure: if set to `True`, a new object will be created and
                   remembered on the context if it's not there yet.


def command(name=None, cls=None, **attrs):

if cls is None:<EOL><INDENT>cls = Command<EOL><DEDENT>def decorator(f):<EOL><INDENT>cmd = _make_command(f, name, attrs, cls)<EOL>cmd.__doc__ = f.__doc__<EOL>return cmd<EOL><DEDENT>return decorator<EOL>

Creates a new :class:`Command` and uses the decorated function as
    callback.  This will also automatically attach all decorated
    :func:`option`\s and :func:`argument`\s as parameters to the command.

    The name of the command defaults to the name of the function.  If you
    want to change that, you can pass the intended name as the first
    argument.

    All keyword arguments are forwarded to the underlying command class.

    Once decorated the function turns into a :class:`Command` instance
    that can be invoked as a command line utility or be attached to a
    command :class:`Group`.

    :param name: the name of the command.  This defaults to the function
                 name.
    :param cls: the command class to instantiate.  This defaults to
                :class:`Command`.


attrs.setdefault('<STR_LIT>', Group)<EOL>return command(name, **attrs)<EOL>

Creates a new :class:`Group` with a function as callback.  This
    works otherwise the same as :func:`command` just that the `cls`
    parameter is set to :class:`Group`.