Merge pull request #109 from iKevinY/doc-fixes
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Documentation Fixes
authored by Armin Ronacher · committed by Armin Ronacher · parents 1b9e2c0, 98910c1 · Browse files · 16 files·+289 added−291 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+289 added−291 removed
- other:+289 added−291 removed
Provenance
- Commit
d428e69- Tree
21863d0- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
1b9e2c0- Parent 2
98910c1
16 files changed+289 added−291 removed
modified:docs/advanced.rst+18 added-18 removed
11 unmodified lines12 13 Command Aliases14 ---------------15 16-Many tools support aliases for commands. For instance you can configure16+Many tools support aliases for commands. For instance, you can configure17 ``git`` to accept ``git ci`` as alias for ``git commit``. Other tools18 also support auto discovery for aliases by automatically shortening them.19 20 Click does not support this out of the box but it's very easy to customize21 the :class:`Group` or any other :class:`MultiCommand` to provide this22 functionality.23 24-As explained in :ref:`custom-multi-commands` a multi command can provide24+As explained in :ref:`custom-multi-commands`, a multi command can provide25 two methods: :meth:`~MultiCommand.list_commands` and26 :meth:`~MultiCommand.get_command`. In this particular case you only need27 to override the latter as you generally don't want to enumerate the28 aliases on the help page to avoid confusion.29 30 This following example implements a subclass of :class:`Group` that31-accepts a prefix for a command. So if there is a command called32-``push`` it would accept ``pus`` as alias if it's unique:31+accepts a prefix for a command. If there is a command called32+``push`` it would accept ``pus`` as an alias if it's unique:33 34 .. click:example::35 36 class AliasedGroup(click.Group):9 unmodified lines46 elif len(matches) == 1:47 return click.Group.get_command(self, ctx, matches[0])48 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))49 50-And it can be used like this then:50+And it can then be used like this:51 52 .. click:example::53 54 @click.command(cls=AliasedGroup)10 unmodified lines65 66 Invoking Other Commands67 -----------------------68 69-Sometimes it might be interesting to invoke one command from another70-command. This is generally a pattern that is discouraged with click but69+Sometimes, it might be interesting to invoke one command from another70+command. This is a pattern that is generally discouraged with click but71 possible nonetheless. For this you can use the :func:`Context.invoke`72 or :func:`Context.forward` methods.73 74-They work similar but the difference is that :func:`Context.invoke` merely74+They work similarly, but the difference is that :func:`Context.invoke` merely75 invokes another command with the arguments you provide as a caller,76 whereas :func:`Context.forward` fills in the arguments from the current77-command. Both accept the command as first argument and everything else is78-passed onwards as you would expect.77+command. Both accept the command as the first argument and everything else78+is passed onwards as you would expect.79 80 Example:81 82 .. click:example::37 unmodified lines120 The main difference is that in optparse callbacks are invoked with the raw121 value as it happens, whereas a callback in click is invoked after the122 value has been fully converted.123 124-Generally the order of invocation is driven by the order in which the user125-provides the arguments to the script. So if there is an option called126-``--foo`` and an option called ``--bar`` and the user calls it as ``--bar127---foo`` then the callback for ``bar`` will fire before the one for ``foo``.124+Generally, the order of invocation is driven by the order in which the user125+provides the arguments to the script; if there is an option called ``--foo``126+and an option called ``--bar`` and the user calls it as ``--bar127+--foo``, then the callback for ``bar`` will fire before the one for ``foo``.128 129 There are two exceptions to this rule which are important to know:130 131 Eagerness:1 unmodified line133 evaluated before all non-eager parameters, but again in the order as134 they were provided on the command line by the user.135 136 This is important for parameters that execute and exit like ``--help``137- and ``--version``. Both are eager parameters but whatever parameter137+ and ``--version``. Both are eager parameters, but whatever parameter138 comes first on the command line will win and exit the program.139 140 Repeated parameters:141 If an option or argument is split up on the command line into multiple142 places because it's repeated (for instance ``--exclude foo --include143- baz --exclude bar``) the callback will fire based on the position of144- the first option. So in this case the callback will fire for143+ baz --exclude bar``), the callback will fire based on the position of144+ the first option. In this case, the callback will fire for145 ``exclude`` and it will be passed both options (``foo`` and146 ``bar``), then the callback for ``include`` will fire with ``baz``147 only.148 2 unmodified lines151 value except the first. The reason for this is to allow composability152 through shell aliases that set defaults.153 154 Missing parameters:155- If a parameter is not defined on the command line the callback will155+ If a parameter is not defined on the command line, the callback will156 still fire. This is different from how it works in optparse where157 undefined values do not fire the callback. Missing parameters fire158 their callbacks at the very end which makes it possible for them to159 default to values from a parameter that came before.3 unmodified linesmodified:docs/arguments.rst+24 added-24 removed
67 unmodified lines68 69 If you come from ``argparse`` you might be missing support for setting70 ``nargs`` to ``+`` to indicate that at least one argument is required.71 72- This is supported by setting ``required=True``. However this should72+ This is supported by setting ``required=True``. However, this should73 not be used if you can avoid it as we believe scripts should gracefully74 degrade into becoming noops if a variadic argument is empty. The75- reason for this is that very often scripts are invoked with wildcard75+ reason for this is that very often, scripts are invoked with wildcard76 inputs from the command line and they should not error out if the77 wildcard is empty.78 79 .. _file-args:80 81 File Arguments82 --------------83 84-Since all the examples have already worked with file names it makes sense84+Since all the examples have already worked with filenames, it makes sense85 to explain how to deal with files properly. Command line tools are more86-fun if they work with files the unix way which is to accept ``-`` as a86+fun if they work with files the Unix way which is to accept ``-`` as a87 special file that refers to stdin/stdout.88 89 Click supports this through the :class:`click.File` type which90-intelligently handles files for you. It also deals with unicode and bytes90+intelligently handles files for you. It also deals with Unicode and bytes91 correctly for all versions of Python so your script stays very portable.92 93 Example:94 27 unmodified lines122 will be a unicode value always. Filenames unfortunately however can be123 unicode or bytes depending on which operating system you're on. As such124 the type is insufficient.125 126-Instead you should be using the :class:`Path` type which handles this127-complexity for you. Not only will it return either bytes or unicode126+Instead, you should be using the :class:`Path` type which handles this127+complexity for you. Not only will it return either bytes or Unicode128 depending on what makes more sense, but it will also be able to do some129 basic checks for you such as existence checks.130 131 Example:23 unmodified lines155 The :class:`FileType` type has one problem it needs to deal with and that156 is to decide when to open a file. The default behavior is to be157 "intelligent" about it. What this means is that it will open stdin/stdout158 and files opened for reading immediately. This will directly give the159-user feedback when a file cannot be opened. But it will only open files159+user feedback when a file cannot be opened, but it will only open files160 for writing the first time an IO operation is performed by wrapping the161 file automatically in a special wrapper.162 163 This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to164-the constructor. If the file is openened lazily it will fail on first IO164+the constructor. If the file is opened lazily, it will fail on first IO165 operation by raising an :exc:`FileError`.166 167-Since files opened for writing will typically immediatley empty the file,168-the lazy mode should really only be disabled if the developer is 100% sure167+Since files opened for writing will typically immediately empty the file,168+the lazy mode should only be disabled if the developer is absolutely sure169 that this is intended behavior.170 171-Forcing on lazy mode is also very useful to avoid resource handling172-confusion. If a file is opened in lazy mode it will get a173-``close_intelligently`` method that can help you figuring out if the file174-needs closing or not. This is not needed for parameters, but it is171+Forcing lazy mode is also very useful to avoid resource handling172+confusion. If a file is opened in lazy mode, it will receive a173+``close_intelligently`` method that can help figure out if the file174+needs closing or not. This is not needed for parameters, but is175 necessary for manually prompting with the :func:`prompt` function as you176-do not know if a stream like stdout was openend (which was already open176+do not know if a stream like stdout was opened (which was already open177 before) or a real file that needs closing.178 179 Starting with click 2.0 it's also possible to open files in atomic mode by180-passing ``atomic=True``. In atomic mode all writes go into a separate180+passing ``atomic=True``. In atomic mode, all writes go into a separate181 file in the same folder and upon completion the file will be moved over to182 the original location. This is useful if a file regularly read by other183 users is modified.184 185 Environment Variables186 ---------------------187 188 Like options, arguments can also get values from an environment variable.189-Unlike options however this is only supported for explicitly named189+Unlike options, however, this is only supported for explicitly named190 environment variables.191 192 Example usage:193 12 unmodified lines206 with open('hello.txt', 'w') as f:207 f.write('Hello World!')208 invoke(echo, env={'SRC': 'hello.txt'})209 210-In that case it can also be a list of different environment variables210+In that case, it can also be a list of different environment variables211 where the first one is picked.212 213 Generally this feature is not recommended because it can cause a lot of214 confusion to the user.215 216-Arguments looking like Options216+Arguments-Like Options217 ------------------------------218 219 Sometimes you want to process arguments that look like options. For220-instance imagine you have a file named ``-foo.txt``. If you pass this as221-such as an argument click will treat it as an option.220+instance, imagine you have a file named ``-foo.txt``. If you pass this as221+an argument in this manner, click will treat it as an option.222 223-To solve this, click does what any POSIX style command line script does223+To solve this, click does what any POSIX style command line script does,224 and that is to accept the string ``--`` as a separator for options and225-arguments. After the ``--`` marker all further parameters are accepted as225+arguments. After the ``--`` marker, all further parameters are accepted as226 arguments.227 228 Example usage:229 13 unmodified linesmodified:docs/bashcomplete.rst+13 added-13 removed
1 unmodified line2 =============3 4 .. versionadded:: 2.05 6-Starting with click 2.0 there is built-in support for bash completion for6+As of click 2.0, there is built-in support for Bash completion for7 any click script. There are certain restrictions on when this completion8-is available but for the most part it should just work.8+is available, but for the most part it should just work.9 10 Limitations11 -----------12 13 Bash completion is only available if a script has been installed properly14 and not executed through the ``python`` command. For information about15-how to do that see :ref:`setuptools-integration`. Currently click also15+how to do that see :ref:`setuptools-integration`. Also, click currently16 only supports completion for bash.17 18-Currently bash completion is an internal feature that is not customizable.18+Currently, bash completion is an internal feature that is not customizable.19 This might be relaxed in future versions.20 21 What it Completes22 -----------------23 24-Generally the bash completion support will complete subcommands and24+Generally, the bash completion support will complete subcommands and25 parameters. Subcommands are always listed whereas parameters only if at26 least a dash has been provided. Example::27 28 $ repo <TAB><TAB>29- clone commit copy delete setuser 29+ clone commit copy delete setuser30 $ repo clone -<TAB><TAB>31- --deep --help --rev --shallow -r 31+ --deep --help --rev --shallow -r32 33 Activation34 ----------35 36-In order to activate bash completion you need to inform bash that36+In order to activate Bash completion you need to inform Bash that37 completion is available for your script and how. Any click application38 automatically provides support for that. The general way this works is39-through a magic environment variable called ``_<PROG_NAME>_COMPLETE``39+through a magic environment variable called ``_<PROG_NAME>_COMPLETE``,40 where ``<PROG_NAME>`` is your application executable name in uppercase41 with dashes replaced by underscores.42 43-So if your tool is called ``foo-bar`` then the magic variable is called43+If your tool is called ``foo-bar``, then the magic variable is called44 ``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will45 spit out the activation script which can be trivally activated.46 47-For instance to enable bash completion for your ``foo-bar`` script, this47+For instance, to enable Bash completion for your ``foo-bar`` script, this48 is what you would need to put into your ``.bashrc``::49 50 eval "$(_FOO_BAR_COMPLETE=source foo-bar)"51 52-From this point onwards your script will have bash completion enabled.52+From this point onwards your script will have Bash completion enabled.53 54 Activation Script55 -----------------56 57 The above activation example will always invoke your application on58 startup. This might be slowing down the shell activation time59 significantly if you have many applications. Alternatively you could also60-ship a file with the contents of that which is what git and other systems60+ship a file with the contents of that which is what Git and other systems61 are doing.62 63 This can be easily accomplished::64 5 unmodified linesmodified:docs/commands.rst+34 added-35 removed
8 unmodified lines9 10 Callback Invocation11 -------------------12 13-For a regular command the callback is executed whenever the command runs.14-So if the script is the only command it will always fire (unless a15-parameter callback prevents it. This for instance happens if someone13+For a regular command, the callback is executed whenever the command runs.14+If the script is the only command it will always fire (unless a15+parameter callback prevents it). This for instance happens if someone16 passes ``--help`` to the script).17 18-For groups and multi commands the situation looks different. In that case18+For groups and multi commands, the situation looks different. In this case,19 the callback fires whenever a subcommand fires (unless this behavior is20 changed). What this means in practice is that an outer command runs21 when an inner command runs:22 18 unmodified lines41 42 Nested Handling and Contexts43 ----------------------------44 45-As you can see from the earlier example the basic command group accepts a45+As you can see from the earlier example, the basic command group accepts a46 debug argument which is passed to its callback, but not to the sync47 command itself. The sync command only accepts its own arguments.48 49-This allows tools to act completely independent of each other. But how49+This allows tools to act completely independent of each other, but how50 does one command talk to a nested one? The answer to this is the51 :class:`Context`.52 53-Each time a command is invoked a new context is created and linked with the54-parent context. Normally you can't see these contexts, but they are53+Each time a command is invoked, a new context is created and linked with the54+parent context. Normally, you can't see these contexts, but they are55 there. Contexts are passed to parameter callbacks together with the56 value automatically. Commands can also ask for the context to be passed57 by marking themselves with the :func:`pass_context` decorator. In that58-case the context is passed as first argument.58+case, the context is passed as first argument.59 60 The context can also carry a program specified object that can be61 used for the program's purposes. What this means is that you can build a62 script like this:13 unmodified lines76 77 if __name__ == '__main__':78 cli(obj={})79 80-If the object is provided each context will pass the object onwards to80+If the object is provided, each context will pass the object onwards to81 its children, but at any level a context's object can be overridden. To82-reach to a parent ``context.parent`` can be used.82+reach to a parent, ``context.parent`` can be used.83 84-In addition to that instead of passing an object down nothing stops the85-application from modifying global state. For instance you could just flip84+In addition to that, instead of passing an object down, nothing stops the85+application from modifying global state. For instance, you could just flip86 a global ``DEBUG`` variable and be done with it.87 88 Decorating Commands89 -------------------90 91-As you have seen in the earlier example a decorator can change how a91+As you have seen in the earlier example, a decorator can change how a92 command is invoked. What actually happens behind the scenes is that93 callbacks are always invoked through the :meth:`Context.invoke` method94 which automatically invokes a command correctly (by either passing the95 context or not).96 97 This is very useful when you want to write custom decorators. For98-instance a common pattern would be to configure an object representing98+instance, a common pattern would be to configure an object representing99 state and then storing it on the context and then to use a custom100 decorator to find the most recent object of this sort and pass it as first101 argument.102 103-For instance the :func:`pass_obj` decorator can be implemented like this:103+For instance, the :func:`pass_obj` decorator can be implemented like this:104 105 .. click:example::106 107 from functools import update_wrapper4 unmodified lines112 return ctx.invoke(f, ctx.obj, *args, **kwargs)113 return update_wrapper(new_func, f)114 115 The :meth:`Context.invoke` command will automatically invoke the function116-in the correct way. So the function will either be called with ``f(ctx,116+in the correct way, so the function will either be called with ``f(ctx,117 obj)`` or ``f(obj)`` depending on if it itself is decorated with118 :func:`with_context`.119 120 This is a very powerful context that can be used to build very complex2 unmodified lines123 124 Group Invocation Without Command125 --------------------------------126 127-By default a group or multi command is not invoked unless a subcommand is127+By default, a group or multi command is not invoked unless a subcommand is128 passed. In fact, not providing a command automatically passes ``--help``129 by default. This behavior can be changed by passing130-``invoke_without_command=True`` to a group. In that case the callback is130+``invoke_without_command=True`` to a group. In that case, the callback is131 always invoked instead of showing the help page. The context object also132-includes information about if the invocation would go to a subcommand or133-not.132+includes information about whether or not the invocation would go to a133+subcommand.134 135 Example:136 137 .. click:example::11 unmodified lines149 click.echo('The subcommand')150 151 And how it works in practice::152 153- $ python tool.py 153+ $ python tool.py154 I was invoked without subcommand155 $ python tool.py sync156 I am about to invoke sync157 The subcommand2 unmodified lines160 161 Custom Multi Commands162 ---------------------163 164-In addition to using :func:`click.group` you can also build your own164+In addition to using :func:`click.group`, you can also build your own165 custom multi commands. This is useful when you want to support commands166 being loaded lazily from plugins.167 168 A custom multi command just needs to implement a list and load method:39 unmodified lines208 209 Merging Multi Commands210 ----------------------211 212-In addition to implementing custom multi commands it can also be212+In addition to implementing custom multi commands, it can also be213 interesting to merge multiple together into one script. While this is214-generally not as recommended as nesting one below the other the merging214+generally not as recommended as nesting one below the other, the merging215 approach can be useful in some circumstances for a nicer shell experience.216 217 A default implementation for such a merging system is the218 :class:`CommandCollection` class. It accepts a list of other multi219-commands and makes the commands available on the same class. It accepts a220-list of other multi commands and makes the commands available on the same221-level.219+commands and makes the commands available on the same level.220 221 Example usage:222 223 .. click:example::26 unmodified lines250 .. click:run::251 252 invoke(cli, prog_name='cli', args=['--help'])253 256-In case a command exists on more than one source, the first source wins.254+In case a command exists in more than one source, the first source wins.255 256 Overriding Defaults257 -------------------258 261-By default the default value for a parameter is pulled from the262-``default`` flag that is provided when it's defined. But that's not the259+By default, the default value for a parameter is pulled from the260+``default`` flag that is provided when it's defined, but that's not the261 only place defaults can be loaded from. The other place is the262 :attr:`Context.default_map` (a dictionary) on the context. This allows265-defaults to be loaded from a config file to override the regular defaults.263+defaults to be loaded from a configuration file to override the regular264+defaults.265 266 This is useful if you plug in some commands from another package but267 you're not satisfied with the defaults.268 269 The default map can be nested arbitrarily for each subcommand and be271-provided when the script is invoked. Alternatively it can also be272-overriden at any point by commands. For instance a toplevel command could273-load the defaults from a config file.270+provided when the script is invoked. Alternatively, it can also be271+overriden at any point by commands. For instance a top-level command could272+load the defaults from a configuration file.273 274 Example usage:275 276 .. click:example::26 unmodified linesmodified:docs/complex.rst+53 added-52 removed
3 unmodified lines4 ====================5 6 .. currentmodule:: click7 8-Click is designed to write complex and simple CLI tools alike. However9-the power of its design is the ability to arbitrarily nest systems10-together. For instance in case you have ever used Django you will have11-realized that it provides a command line utility. But so does Celery for12-instance. So when using Celery with Django there are two tools that need8+Click is designed to assist with the creation of complex and simple CLI tools9+alike. However, the power of its design is the ability to arbitrarily nest10+systems together. For instance, in case you have ever used Django, you will11+have realized that it provides a command line utility, but so does Celery (for12+instance). When using Celery with Django there are two tools that need13 to interact with each other and be cross configured.14 15 In a theoretical world of two separate click command line utilities they16-can solve this problem by nesting one inside the other. For instance the16+can solve this problem by nesting one inside the other. For instance, the17 web framework could also load the commands for the message queue18 framework.19 20 Basic Concepts4 unmodified lines25 26 Contexts27 ````````28 29-Whenever a click command is executed a :class:`Context` object is created30-which holds state for this particular invocation. For instance it31-remembers parsed parameters, what command created it, which resources need32-to be cleaned up at the end of the function and so forth. It also holds33-an application defined object optionally.29+Whenever a click command is executed, a :class:`Context` object is created30+which holds state for this particular invocation. It remembers parsed31+parameters, what command created it, which resources need to be cleaned up32+at the end of the function, and so forth. It can also optionally hold an33+application-defined object.34 35 Context objects build a linked list until they hit top one. Each context36 is linked to the parent context. This allows a command to work below37 another command and store its own information there without having to be38 afraid of messing up the state of the parent command.39 40-Because the parent data is however available it's possible to navigate to40+Because the parent data is available, however, it is possible to navigate to41 it if needed.42 43 Most of the time you don't see the context object, but when writing more44 complex applications it comes in handy. This brings us to the next point.45 46 Calling Convention47 ``````````````````48 49-When a click command callback is executed it's passed all the non hidden50-parameters as keyword arguments. Notably absent is the context. However51-a callback can opt-into being passed the context object by marking itself49+When a click command callback is executed, it's passed all the non-hidden50+parameters as keyword arguments. Notably absent is the context. However,51+a callback can opt into being passed the context object by marking itself52 with :func:`pass_context`.53 54 So how do you invoke a command callback if you don't know if it should55 receive the context or not? The answer is that the context itself56 provides a helper function (:meth:`Context.invoke`) which can do this for57 you. It accepts the callback as first argument and then invokes the58 function correctly.59 60-Building a Git61---------------60+Building a Git Clone61+--------------------62 63 In this example we want to build a command line tool that resembles a64-version control system a bit. Systems like git usually provide one64+version control system. Systems like Git usually provide one65 over-arching command that already accepts some parameters and66-configuration, and then has extra subcommands that do other things.66+configuration, and then have extra subcommands that do other things.67 68 The Root Command69 ````````````````70 71-At the top level we need a group that can hold all our commands. In this72-case we use the basic :func:`click.group` which allows us to register71+At the top level, we need a group that can hold all our commands. In this72+case, we use the basic :func:`click.group` which allows us to register73 other click commands below it.74 75 For this command we also want to accept some parameters that configure the76 state of our tool:21 unmodified lines98 99 So let's understand what this does. We create a group command which can100 have subcommands. When it is invoked it will create an instance of a101 ``Repo`` class. This holds the state for our command line tool. In this102-case it just remembers some parameters but at this point it could also103-start loading config files and so on.102+case it just remembers some parameters, but at this point it could also103+start loading configuration files and so on.104 105 This state object is then remembered as :attr:`~Context.obj` on the106 context. This is a special attribute where commands are supposed to107 remember what they need to pass on to their children.108 109-In order for this to work we need to mark our function with110-:func:`pass_context` because otherwise the context object would be109+In order for this to work, we need to mark our function with110+:func:`pass_context`, because otherwise the context object would be111 entirely hidden from us.112 113 The First Child Command114 ```````````````````````115 116-So let's add our first child command to it. Let's go with the clone117-command:116+Let's add our first child command to it, the clone command:117 118 .. click:example::119 120 @cli.command()2 unmodified lines123 def clone(src, dest):124 pass125 126 So now we have a clone command, but how do we get access to the repo? As128-you can imagine one way is to use the :func:`pass_context` function which127+you can imagine, one way is to use the :func:`pass_context` function which128 again will make our callback also get the context passed on which we130-memorized the repo. Even better there is a second version of this131-decorator called :func:`pass_obj` which will just pass the stored object,132-in our case the repo:129+memorized the repo. However, there is a second version of this decorator130+called :func:`pass_obj` which will just pass the stored object, (in our case131+the repo):132 133 .. click:example::134 135 @cli.command()5 unmodified lines141 142 Interleaved Commands143 ````````````````````144 146-While not relevant for this particular program we want to build there is147-also quite good support for interleaving systems. Imagine for instance145+While not relevant for the particular program we want to build, there is146+also quite good support for interleaving systems. Imagine for instance that147 there would be this super cool plugin for our version control system that148 needs a lot of configuration and wants to store its own configuration as149 :attr:`~Context.obj`. If we would then attach another command below that,151-all the sudden we would get the plugin config instead of our repo object.150+we would all of a sudden get the plugin configuration instead of our repo151+object.152 153-One obvious way is to store a reference to the repo on the plugin but then154-a command needs to be aware that it's attached below such a plugin.153+One obvious way to remedy this is to store a reference to the repo in the154+plugin, but then a command needs to be aware that it's attached below such a155+plugin.156 156-There is a much better system by taking advantage of the linked nature of157-contexts. We know that the plugin context is linked to the context that158-created our repo. Because of that we can start a search for the last157+There is a much better system that can built by taking advantage of the linked158+nature of contexts. We know that the plugin context is linked to the context159+that created our repo. Because of that, we can start a search for the last160 level where the object stored on the context was a repo.161 162 Built-in support for this is provided by the :func:`make_pass_decorator`162-factory which will create decorators for us that find objects (it163-internally calls into :meth:`Context.find_object`). So in our case we164-know that we want to find the closest ``Repo`` object. So let's make a163+factory, which will create decorators for us that find objects (it164+internally calls into :meth:`Context.find_object`). In our case, we165+know that we want to find the closest ``Repo`` object, so let's make a166 decorator for this:167 168 .. click:example::169 170 pass_repo = click.make_pass_decorator(Repo)171 171-If we now use ``pass_repo`` instead of ``pass_obj`` we will always get a172+If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a173 repo instead of something else:174 175 .. click:example::176 3 unmodified lines180 @pass_repo181 def clone(repo, src, dest):182 pass183 183-Ensuring Objects184-````````````````184+Ensuring Object Creation185+````````````````````````186 187 The above example only works if there was an outer command that created a188 ``Repo`` object and stored it on the context. For some more advanced use188-cases this might be a problem for you. The default behavior of189-:func:`make_pass_decorator` is to call into :meth:`Context.find_object`190-which will find the object. If it can't find the object it will raise an189+cases, this might become a problem. The default behavior of190+:func:`make_pass_decorator` is to call :meth:`Context.find_object`191+which will find the object. If it can't find the object, it will raise an192 error. The alternative behavior is to use :meth:`Context.ensure_object`192-which will find the object, or if it cannot find it, will create one and193+which will find the object, and if it cannot find it, will create one and194 store it on the innermost context. This behavior can also be enabled for195 :func:`make_pass_decorator` by passing ``ensure=True``:196 197 .. click:example::198 199 pass_repo = click.make_pass_decorator(Repo, ensure=True)200 200-In this case the innermost context gets such an object created if it's201+In this case, the innermost context gets an object created if it is202 missing. This might replace objects being placed there earlier. In this202-case the command stays executable, even if the outer command does not run.203-For this to work the object type needs to have a constructor that accepts203+case, the command stays executable, even if the outer command does not run.204+For this to work, the object type needs to have a constructor that accepts205 no arguments.206 207 As such it runs standalone:208 12 unmodified linesmodified:docs/documentation.rst+15 added-15 removed
1 Documenting Scripts2 ===================3 4 Click makes it very easy to document your command line tools. First of5-all it automatically generates help pages for you. While these are6-currently not customizable in layout, all the texts can be changed.5+all, it automatically generates help pages for you. While these are6+currently not customizable in layout, all of the text can be changed.7 8 Help Texts9 ----------10 11-Commands and options accept help arguments. In case of commands the doc11+Commands and options accept help arguments. In the case of commands, the doc12 string of the function is automatically used if provided.13 14 Simple example:15 13 unmodified lines29 30 invoke(hello, args=['--help'])31 32 Arguments cannot be documented this way. This is to follow general33-convention of Unix tools to use arguments only for the most necessary33+convention of Unix tools using arguments for only the most necessary34 things and to document them in the introduction text by referring to them35 by name.36 37 Preventing Rewrapping38 ---------------------39 40 The default behavior of click is to rewrap text to work correctly for the41-width of the terminal. In some circumstances this can become a problem.41+width of the terminal. In some circumstances, this can become a problem.42 The main issue is showing code examples where newlines are significant.43 44-Rewrapping can be disabled on a per-paragraph case by adding a line with45-just the ``\b`` escape marker in it. This line will be removed from the44+Rewrapping can be disabled on a per-paragraph basis by adding a line with45+solely the ``\b`` escape marker in it. This line will be removed from the46 help text and rewrapping will be disabled.47 48 Example:49 23 unmodified lines73 74 invoke(cli, args=['--help'])75 76 77-Meta Vars78----------77+Meta Variables78+--------------79 80 Options and parameters accept a ``metavar`` argument that can change the81 meta variable in the help page. The default version is the parameter name82-in uppercase with underscores and sometimes annotated differently if83-optional. This can be customized at all levels:82+in uppercase with underscores, but can be annotated differently if83+desired. This can be customized at all levels:84 85 .. click:example::86 87 @click.command(options_metavar='<options>')9 unmodified lines97 98 .. click:run::99 100 invoke(hello, args=['--help'])101- 101 102+103 Command Short Help104 ------------------105 106-For commands a short help is generated. By default it's the first part107-(until the first dot) of the help message of the command unless it's too108-long. This can also be overridden:106+For commands, a short help snippet is generated. By default, it's the first107+sentence of the help message of the command, unless it's too long. This can108+also be overridden:109 110 .. click:example::111 112 @click.group()16 unmodified linesmodified:docs/license.rst+3 added-3 removed
1 License2 =======3 4-Click is licensed under a three clause BSD License. It basically means:5-do whatever you want with it as long as the copyright in Click sticks4+Click is licensed under a three-clause BSD License. It basically means:5+do whatever you want with it as long as the copyright in click sticks6 around, the conditions are not modified and the disclaimer is present.7-Furthermore you must not use the names of the authors to promote derivatives7+Furthermore, you must not use the names of the authors to promote derivatives8 of the software without written consent.9 10 License Text11 ------------2 unmodified linesmodified:docs/options.rst+38 added-39 removed
2 unmodified lines3 4 .. currentmodule:: click5 6 Adding options to commands can be accomplished by the :func:`option`7-decorator. Since options can come in various different versions there7+decorator. Since options can come in various different versions, there8 are a ton of parameters to configure their behavior.9 10 Basic Value Options11 -------------------12 13 The most basic option is a value option. These options accept one14-argument which is a value. If no type is provided the type of the default14+argument which is a value. If no type is provided, the type of the default15 value is used. If no default value is provided the type is assumed to be16-:data:`STRING`. The name of the parameter is by default the first long17-option defined, otherwise the first short one.16+:data:`STRING`. By default, the name of the parameter is the first long17+option defined; otherwise the first short one is used.18 19 .. click:example::20 21 @click.command()12 unmodified lines34 35 Multi Value Options36 -------------------37 38-Sometimes you have options that take more than one argument. For options38+Sometimes, you have options that take more than one argument. For options,39 only a fixed number of arguments is supported. This can be configured by40 the ``nargs`` parameter. The values are then stored as a tuple.41 42 .. click:example::11 unmodified lines54 55 Multiple Options56 ----------------57 58-Similar to ``nargs`` there is also the case where sometimes you want to58+Similar to ``nargs`` there is also the case where you sometimes want to59 support a parameter to be provided multiple times to and have all values60 recorded and not just the last one. For instance ``git commit -m foo -m61 bar`` would record two lines for the commit message. ``foo`` and ``bar``.62 This can be accomplished with the ``multiple`` flag:15 unmodified lines78 79 Counting80 --------81 82-In some very rare circumstances it's interesting to use the repeating of83-options to count an integer up. This for instance can be used for84-verbosity flags:82+In some very rare circumstances, it's interesting to use the repetition83+of options to count an integer up. This can be used for verbosity flags,84+for instance:85 86 .. click:example::87 88 @click.command()11 unmodified lines100 -------------101 102 Boolean flags are options that can be enabled or disabled. This can be103 accomplished by defining two flags in one go separated by a slash (``/``)104-for enabling or disabling the option. (If a slash is in an option string104+for enabling or disabling the option. (If a slash is in an option string,105 click automatically knows that it's a boolean flag and will pass106-``is_flag=True`` implicitly). Click always wants you to provide an enable106+``is_flag=True`` implicitly.) Click always wants you to provide an enable107 and disable flag so that you can change the default later.108 109 Example:110 15 unmodified lines126 127 invoke(info, args=['--shout'])128 invoke(info, args=['--no-shout'])129 130-If you really don't want an off-switch you can just define one and130+If you really don't want an off-switch, you can just define one and131 manually inform click that something is a flag:132 133 .. click:example::134 15 unmodified lines150 151 Feature Switches152 ----------------153 154-In addition to boolean flags there are also feature switches. These are155-implemented by setting multiple options to the same parameter name and by156-defining a flag value. Note that by providing the ``flag_value`` parameter154+In addition to boolean flags, there are also feature switches. These are155+implemented by setting multiple options to the same parameter name and156+defining a flag value. Note that by providing the ``flag_value`` parameter,157 click will implicitly set ``is_flag=True``.158 159-To set a default flag assign a value of `True` to the flag that should be159+To set a default flag, assign a value of `True` to the flag that should be160 the default.161 162 .. click:example::163 46 unmodified lines210 211 Prompting212 ---------213 214-Sometimes you want parameters that can either be provided from the command215-line or if not, you want to ask for user input. This can be implemented216-with click by defining a prompt string.214+Sometimes, you want parameters that can be provided from the command line,215+but if not, ask for user input. This can be implemented with click by216+defining a prompt string.217 218 Example:219 220 .. click:example::9 unmodified lines230 231 invoke(hello, args=['--name=John'])232 invoke(hello, input=['John'])233 234-If you are not happy with the default prompt string you can ask for234+If you are not happy with the default prompt string, you can ask for235 a different one:236 237 .. click:example::238 27 unmodified lines266 .. click:run::267 268 invoke(encrypt, input=['secret', 'secret'])269 270-Because this combination of parameters is quite common this can also be270+Because this combination of parameters is quite common, this can also be271 replaced with the :func:`password_option` decorator:272 273 .. click:example::274 5 unmodified lines280 Callbacks and Eager Options281 ---------------------------282 283 Sometimes you want a parameter to completely change the execution flow.284-This for instance is the case when you want to have a ``--version``284+For instance, this is the case when you want to have a ``--version``285 parameter that prints out the version and then exits the application.286 287 In such cases you need two concepts: eager parameters and a callback. An288 eager parameter is a parameter that is handled before others and a25 unmodified lines314 def hello():315 click.echo('Hello World!')316 317 The `expose_value` parameter prevents the now pretty pointless ``version``318-parameter to be passed to the callback. If that was not specified a318+parameter to be passed to the callback. If that was not specified, a319 boolean would be passed to the `hello` script. The `resilient_parsing`320 flag is set on the context if click wants to parse the command line321 without and destructive behavior that would change the execution flow. In322-this case because we would exit the program, we instead do nothing in that323-case.322+this case, because we would exit the program, we instead do nothing.323 324 What it looks like:325 326 .. click:run::8 unmodified lines335 336 Yes Parameters337 --------------338 340-For dangerous operations it's very useful to be able to ask a user for339+For dangerous operations, it's very useful to be able to ask a user for340 confirmation. This can be done by adding a boolean ``--yes`` flag and341 asking for confirmation if the user did not provide it and to fail in a342 callback:343 16 unmodified lines360 361 invoke(dropdb, input=['n'])362 invoke(dropdb, args=['--yes'])363 365-Because this combination of parameters is quite common this can also be364+Because this combination of parameters is quite common, this can also be365 replaced with the :func:`confirmation_option` decorator:366 367 .. click:example::368 11 unmodified lines380 ---------------------------------381 382 A very useful feature of click is the ability to accept parameters from383 environment variables in addition to regular parameters. This allows385-tools to be automated much easier. For instance you might want to pass386-the config file as ``--config`` parameter but also support exporting a387-``TOOL_CONFIG=hello.cfg`` key / value pair for a nicer development384+tools to be automated much easier. For instance, you might want to pass385+a configuration file with a ``--config`` parameter but also support exporting386+a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development387 experience.388 389 This is supported by click in two ways. One is to automatically build390 environment variables which is supported for options only. To enable this392-feature the ``auto_envvar_prefix`` parameter needs to be passed to the393-script that is invoked. Each command and parameter is then added as394-underscore-separated variable in uppercase. So if you have a subcommand391+feature, the ``auto_envvar_prefix`` parameter needs to be passed to the392+script that is invoked. Each command and parameter is then added as an393+uppercase underscore-separated variable. If you have a subcommand394 called ``foo`` taking an option called ``bar`` and the prefix is396-``MY_TOOL`` then the variable is ``MY_TOOL_FOO_BAR``.395+``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.396 397 Example usage:398 399 .. click:example::49 unmodified lines449 450 The default implementation for all types is to split on whitespace. The451 exceptions to this rule are the :class:`File` and :class:`Path` types452 which both split according to the operating system's path splitting rules.454-On UNIX systems like Linux and OS X the splitting happens for those on455-every colon (``:``) and for Windows on a semicolon (``;``).453+On UNIX systems like Linux and OS X, the splitting happens for those on454+every colon (``:``), and for Windows, on every semicolon (``;``).455 456 Example usage:457 458 .. click:example::49 unmodified lines508 A special mention should go to the :class:`IntRange` type which works very509 similar to the :data:`INT` type but restricts the value to fall into a510 specific range (inclusive on both edges). It has two modes:511 513-- the default mode (non clamping mode) where a value that falls outside512+- the default mode (non-clamping mode) where a value that falls outside513 of the range will cause an error.514 - an optional clamping mode where a value that falls outside of the515 range will be clamped. This means that a range of ``0-5`` would516 return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for18 unmodified lines535 536 invoke(repeat, args=['--count=1000', '--digit=5'])537 invoke(repeat, args=['--count=1000', '--digit=12'])538 540-If you pass ``None`` for any of the edges it means that the range is open539+If you pass ``None`` for any of the edges, it means that the range is open540 at that side.541 542 Callbacks for Validation543 ------------------------4 unmodified lines548 parameter callbacks. These callbacks can both modify values as well as549 raise errors if the validation does not work.550 551 In click 1.0 you can only raise the :exc:`UsageError` but starting with553-click 2.0 you can also raie the :exc:`BadParameter` error which has the552+click 2.0 you can also raise the :exc:`BadParameter` error which has the553 added advantage that it will automatically format the error message to554 also contain the parameter name.555 556 Example:25 unmodified linesmodified:docs/parameters.rst+6 added-6 removed
8 unmodified lines9 name indicates an option is optional. While arguments can be optional10 within reason they are much more restricted in how they can be optional.11 12 To help you decide between options and arguments, the recommendation is13-to use arguments exclusively for things like going to subcommands or input 13+to use arguments exclusively for things like going to subcommands or input14 filenames / URLs and have everything else be an option instead.15 16 Differences17 -----------49 unmodified lines67 .. autoclass:: IntRange68 :noindex:69 70 Custom parameter types can be implemented by subclassing71-:class:`click.ParamType`. For simple cases passing a python function that72-fails with a `ValueError` is also supported though discouraged.71+:class:`click.ParamType`. For simple cases, passing a Python function that72+fails with a `ValueError` is also supported, though discouraged.73 74 Parameter Names75 ---------------76 12 unmodified lines89 90 Implementing Custom Types91 -------------------------92 93-To implement a custom type you need to subclass the :class:`ParamType`93+To implement a custom type, you need to subclass the :class:`ParamType`94 class. Types can be invoked with or without context and parameter object95 which is why they need to be able to deal with this.96 97-The following code implements an integer type that accepts hex, octal97+The following code implements an integer type that accepts hex and octal98 numbers in addition to normal integers and converts them into regular99 integers::100 101 import click12 unmodified lines114 self.fail('%s is not a valid integer' % value, param, ctx)115 116 BASED_INT = BasedIntParamType()117 118-As you can see a subclass needs to implement the :meth:`ParamType.convert`118+As you can see, a subclass needs to implement the :meth:`ParamType.convert`119 method and optionally provide the :attr:`ParamType.name` attribute. The120 latter can be used for documentation purposes.modified:docs/prompts.rst+9 added-9 removed
7 unmodified lines8 prompts at a later point independently.9 10 This can be accomplished with the :func:`prompt` function which asks for11 valid input according to a type or the :func:`confirm` function which asks12-for confirmation (yes / no).12+for confirmation (yes/no).13 14 Option Prompts15 --------------16 17 Option prompts are integrated into the option interface. See18-:ref:`option-prompting` for more information. Internally it18+:ref:`option-prompting` for more information. Internally, it19 automatically calls into :func:`prompt` or :func:`confirm` as necessary.20 21 Input Prompts22 -------------23 24-To manually ask for user input you can use the :func:`prompt` function.25-By default it accepts any unicode string but you can ask for any other24+To manually ask for user input, you can use the :func:`prompt` function.25+By default, it accepts any Unicode string, but you can ask for any other26 type. For instance you can ask for a valid integer::27 28 value = click.prompt('Please enter a valid integer', type=int)29 30-The type is also automatically detected if a default is provided. The31-following for instance will only accept floats::30+The type is also automatically detected if a default is provided. For31+instance, the following will only accept floats::32 33 value = click.prompt('Please enter a number', default=42.0)34 35 Confirmation Prompts36 --------------------37 38-To ask if a user wants to continue with an action the :func:`confirm`39-function comes in handy. By default it returns the result of the prompt40-as boolean value::38+To ask if a user wants to continue with an action, the :func:`confirm`39+function comes in handy. By default, it returns the result of the prompt40+as a boolean value::41 42 if click.confirm('Do you want to continue?'):43 click.echo('Well done!')44 3 unmodified linesmodified:docs/python3.rst+23 added-23 removed
21 unmodified lines22 While there are encoding hints for all of this, there are generally23 some situations where this can break. The most common one is SSH24 connections to machines with different locales.25 26- Misconfigured environments can currently cause a wide range of unicode26+ Misconfigured environments can currently cause a wide range of Unicode27 problems on Python 3 due to the lack of support for roundtripping28 surrogate escapes. This will not be fixed in click itself!29 30 For more information see :ref:`python3-surrogates`.16 unmodified lines47 sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')48 out_stream = io.BytesIO()49 sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')50 51- Remember that in that case you need to use ``out_stream.getvalue()``51+ Remember that in that case, you need to use ``out_stream.getvalue()``52 and not ``sys.stdout.getvalue()`` if you want to access the buffer53 contents as the wrapper will not forward that method.54 55-Python 2 / 3 Differences55+Python 2 and 3 Differences56 ------------------------57 58 Click attempts to minimize the differences between Python 2 and Python 359 by following the best practices for both languages.60 61-On Python 2 the following is true:61+On Python 2, the following is true:62 63 * ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` are opened in binary64- mode but under some circumstances they support unicode output. Click64+ mode, but under some circumstances they support Unicode output. Click65 attempts to not subvert this but provides support for forcing streams66- to be unicode-based.66+ to be Unicode-based.67 * ``sys.argv`` is always bytes-based. Click will pass bytes to all68 input types and convert as necessary. The :class:`STRING` type69 automatically will decode properly the input value into a string by70 trying the most appropriate encodings.71-* When dealing with files, click will never go through the unicode APIs71+* When dealing with files, click will never go through the Unicode APIs72 and will instead use the operating system's byte APIs to open the73 files.74 75-On Python 3 the following is true:75+On Python 3, the following is true:76 77 * ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default78 text-based. When click needs a binary stream, it attempts to discover79 the underlying binary stream. See :ref:`python3-limitations` for how80 this works.81-* ``sys.argv`` is always unicode-based. This also means that the native82- type for input values to the types in click is unicode and not bytes.81+* ``sys.argv`` is always Unicode-based. This also means that the native82+ type for input values to the types in click is Unicode and not bytes.83 84 This causes problems when the terminal is incorrectly set and Python85- does not figure out the encoding. In that case the unicode string85+ does not figure out the encoding. In that case, the Unicode string86 will contain error bytes encoded as surrogate escapes.87-* When dealing with files, click will always use the unicode file system87+* When dealing with files, click will always use the Unicode file system88 API calls by using the operating system's reported or guessed89 filesystem encoding. Surrogates are supported for filenames, so it90 should be possible to open files through the :class:`File` type even91 if the environment is misconfigured.2 unmodified lines94 95 Python 3 Surrogate Handling96 ---------------------------97 98-Click on Python 3 does all the unicode handling in the standard library99-and is subject to its behavior. On Python 2 click does all the unicode98+Click on Python 3 does all the Unicode handling in the standard library99+and is subject to its behavior. On Python 2 click does all the Unicode100 handling itself which means there are differences in error behavior.101 102-The most glaring difference is that on Python 2 unicode will "just work"102+The most glaring difference is that on Python 2, Unicode will "just work",103 but requires extra care on Python 3. The reason for this is that on104-Python 3 the encoding detection is done in the interpreter and on Linux104+Python 3, the encoding detection is done in the interpreter and on Linux105 and certain other operating systems its encoding handling is problematic.106 107-The biggest source of frustration there is that click scripts invoked by107+The biggest source of frustration is that click scripts invoked by108 init systems (sysvinit, upstart, systemd, etc.), deployment tools (salt,109-puppet) or cron jobs (cron) will refuse to work unless a unicode locale is109+puppet) or cron jobs (cron) will refuse to work unless a Unicode locale is110 exported.111 112 If click encounters such an environment it will prevent further execution113 to force you to set a locale. This is done because click cannot know114 about the state of the system once it's invoked and restore the values115-before Python's unicode handling kicked in.115+before Python's Unicode handling kicked in.116 117 If you see something like this error on Python 3::118 119 Traceback (most recent call last):3 unmodified lines123 to Python 2 or consult for http://click.pocoo.org/python3/124 mitigation steps.125 126 You are dealing with an environment where Python 3 thinks you are127-restricted to ASCII data. The solution for these problems is different127+restricted to ASCII data. The solution to these problems is different128 depending on which locale your computer is running in.129 130-For instance if you have a German linux machine you can fix the problem130+For instance if you have a German Linux machine you can fix the problem131 by exporting the locale to ``de_DE.utf-8``::132 133 export LC_ALL=de_DE.utf-8134 export LANG=de_DE.utf-8135 136 If you are on a US machine, ``en_EN.utf-8`` is the encoding of choice. On137-some newer linux systems you can also try ``C.UTF-8`` as locale::137+some newer Linux systems you can also try ``C.UTF-8`` as locale::138 139 export LC_ALL=C.UTF-8140 export LANG=C.UTF-8141 7 unmodified lines149 <http://bugs.python.org/issue19977>`_150 * `Python 3 raises Unicode errors in the C locale151 <http://bugs.python.org/issue19846>`_152 * `LC_CTYPE=C: pydoc leaves terminal in an unusable state153- <http://bugs.python.org/issue21398>`_ (this is relevant to Click153+ <http://bugs.python.org/issue21398>`_ (this is relevant to click154 because the pager support is provided by the stdlib pydoc module)modified:docs/quickstart.rst+10 added-11 removed
38 unmodified lines39 40 Basic Concepts41 --------------42 43-Click is based on declaring commands through decorators. Internally there44-is a non-decorator interface for advanced use cases but it's discouraged43+Click is based on declaring commands through decorators. Internally, there44+is a non-decorator interface for advanced use cases, but it's discouraged45 for high-level usage.46 47 A function becomes a click command line tool by decorating it through48-:func:`click.command`. In the most simple version just decorating a49-function with this decorator will make it into a callable script:48+:func:`click.command`. At its simplest, just decorating a function49+with this decorator will make it into a callable script:50 51 .. click:example::52 53 import click33 unmodified lines87 What this means is that the :func:`echo` function applies some error88 correction in case the terminal is misconfigured instead of dying with an89 :exc:`UnicodeError`.90 91-As an added benefit, starting with click 2.0 the echo function also91+As an added benefit, starting with click 2.0, the echo function also92 has good support for ANSI colors. It will automatically strip ANSI codes93 if the output stream is a file and if colorama is supported, ANSI colors94 will also work on Windows. See :ref:`ansi-colors` for more information.95 23 unmodified lines119 120 cli.add_command(initdb)121 cli.add_command(dropdb)122 123-As you can see the :func:`group` decorator works like the :func:`command`124-decorator but creates a :class:`Group` object instead which can be given125-multiple subcommands that can be attached with126-:meth:`Group.add_command`.123+As you can see, the :func:`group` decorator works like the :func:`command`124+decorator, but creates a :class:`Group` object instead which can be given125+multiple subcommands that can be attached with :meth:`Group.add_command`.126 128-For simple scripts it's also possible to automatically attach and create a127+For simple scripts, it's also possible to automatically attach and create a128 command by using the :meth:`Group.command` decorator instead. The above129 script can be written like this then:130 131 .. click:example::12 unmodified lines144 145 Adding Parameters146 -----------------147 149-To add parameters the :func:`option` and :func:`argument` decorators:148+To add parameters, use the :func:`option` and :func:`argument` decorators:149 150 .. click:example::151 152 @click.command()11 unmodified linesmodified:docs/setuptools.rst+3 added-3 removed
17 unmodified lines18 Introduction19 ------------20 21 All you need to do to bundle your scripts with setuptools is your script22-in a python package and a ``setup.py`` file.22+in a Python package and a ``setup.py`` file.23 24-Imagine this layout::24+Imagine this directory structure::25 26 yourpackage/27 cli.py28 setup.py26 unmodified lines55 yourscript=yourpackage.cli:cli56 ''',57 )58 59-The magic is in the ``entry_points`` parameter. Below ``console_scripts``59+The magic is in the ``entry_points`` parameter. Below ``console_scripts``,60 each line identifies one console script. The first part before the equals61 sign (``=``) is the name of the script that should be generated, the second62 part is the import path followed by a colon (``:``) with the click63 command.18 unmodified linesmodified:docs/testing.rst+3 added-3 removed
1 unmodified line2 ==========================3 4 .. currentmodule:: click.testing5 6-For basic testing click provides the :mod:`click.testing` module which6+For basic testing, click provides the :mod:`click.testing` module which7 provides test functionality that helps you invoke command line8 applications and check their behavior.9 10 These tools really only should be used for testing as they are changing29 unmodified lines40 41 File System Isolation42 ---------------------43 44-For basic command line tools that want to operate with the file system the44+For basic command line tools that want to operate with the file system, the45 :meth:`CliRunner.isolated_filesystem` method comes in useful which sets up46 an empty folder and changes the current working directory to.47 48 Example::19 unmodified lines68 Input Streams69 -------------70 71 The test wrapper can also be used to provide input data for the input72-stream (stdin). This is very useful for testing prompts for instance::72+stream (stdin). This is very useful for testing prompts, for instance::73 74 import click75 from click.testing import CliRunner76 14 unmodified linesmodified:docs/utils.rst+23 added-23 removed
21 unmodified lines22 import click23 24 click.echo('Hello World!')25 26-Most importantly it can print both unicode and binary data, unlike the26+Most importantly, it can print both Unicode and binary data, unlike the27 builtin ``print`` function on Python 3 which cannot output any bytes. It28-will however emit a trailing newline by default which needs to be28+will, however, emit a trailing newline by default which needs to be29 supressed by passing ``nl=False``::30 31 click.echo(b'\xe2\x98\x83', nl=False)32 46 unmodified lines79 80 Pager Support81 -------------82 83-In some situations you might want to show long texts on the terminal and83+In some situations, you might want to show long texts on the terminal and84 let a user scroll through it. This can be achieved by using the85 :func:`echo_via_pager` function which works similar to the :func:`echo`86 function but always writes to stdout and, if possible, through a pager.87 13 unmodified lines101 .. versionadded:: 2.0102 103 To clear the terminal screen you can use the :func:`clear` function that104 is provided starting with Click 2.0. It does what the name suggests: it105-clears the entire visible screen in a platform agnostic way:105+clears the entire visible screen in a platform-agnostic way:106 107 ::108 109 import click5 unmodified lines115 116 .. versionadded:: 2.0117 118 Normally when reading input from the terminal you would use reading from119-standard input. However this is buffered input and will not show up until120-the line has been terminated. In certain circumstances you might not want119+standard input. However, this is buffered input and will not show up until120+the line has been terminated. In certain circumstances, you might not want121 to do that and instead read individual characters as they are being122 written.123 124 For this click provides the :func:`getchar` function which reads a single125-character from the terminal buffer and returns it as a unicode character.125+character from the terminal buffer and returns it as a Unicode character.126 127 Note that this function will always read from the terminal, even if stdin128 is instead a pipe.129 39 unmodified lines169 message = click.edit('\n\n' + MARKER)170 if message is not None:171 return message.split(MARKER, 1)[0].rstrip('\n')172 173-Alternatively the function can also be used to launch editors for files by174-a specific filename. In that case the return value is always `None`.173+Alternatively, the function can also be used to launch editors for files by174+a specific filename. In this case, the return value is always `None`.175 176 Example usage::177 178 import click5 unmodified lines184 185 .. versionadded:: 2.0186 187 Click supports launching applications through :func:`launch`. This can be188-used to open the default application assocated with a URL or file type.189-This for instance can be used to both launch web browsers as well as190-picture viewers etc. In addition to that it can also launch the file191-manager and automatically select the provided file.188+used to open the default application assocated with a URL or filetype.189+This for instance can be used to launch web browsers, picture viewers, etc.190+In addition to that, it can also launch the file manager and automatically191+select the provided file.192 193 Example usage::194 195 click.launch('http://click.pocoo.org/')2 unmodified lines198 199 Printing Filenames200 ------------------201 202-Because filenames might not be unicode, formatting them can be a bit202+Because filenames might not be Unicode, formatting them can be a bit203 tricky. Generally this is easier on Python 2 than on 3 as you can just204 write the bytes to stdout with the print function, but at least on Python205-3 you will need to always operate in unicode.205+3 you will need to always operate in Unicode.206 207 The way this works with click is through the :func:`format_filename`208 function. It does a best effort conversion of the filename to Unicode and209 will never fail. This makes it possible to use these filenames in the210-context of a full unicode string.210+context of a full Unicode string.211 212 Example::213 214 click.echo('Path: %s' % click.format_filename(b'foo.txt'))1 unmodified line216 217 Standard Streams218 ----------------219 220-For command line utilities it's very important to get access to input and220+For command line utilities, it's very important to get access to input and221 output streams reliably. Python generally provides access to these222 streams through ``sys.stdout`` and friends, but unfortunately there are223 API differences between 2.x and 3.x. Especially in regards to how these224-streams respond to unicode and binary data there are wide differences.224+streams respond to Unicode and binary data there are wide differences.225 226-Because of this click provides the :func:`get_binary_stream` and226+Because of this, click provides the :func:`get_binary_stream` and227 :func:`get_text_stream` which produce consistent results with different228 Python versions and for widely misconfigured terminals.229 230 The end result is that these functions will always return a functional12 unmodified lines243 ---------------------------244 245 .. versionadded:: 2.0246 247-Very often you want to open a config file that belongs to your248-application. However different operating systems store these config249-files by their policy in different places. Click provides a250-:func:`get_app_dir` function which returns the most appropriate location247+Very often you want to open a configuration file that belongs to your248+application. However, different operating systems store these configuration249+files in different locations depending on their standards. Click provides250+a :func:`get_app_dir` function which returns the most appropriate location251 for per-user config files for your application depending on the OS.252 253 Example usage::254 61 unmodified linesmodified:docs/why.rst+14 added-14 removed
1 Why Click?2 ==========3 4-There are so many libraries out there for writing command line utilities,4+There are so many libraries out there for writing command line utilities;5 why does click exist?6 7 This question is easy to answer: because there is not a single command8 line utility for Python out there which ticks the following boxes:9 unmodified lines18 There are many alternatives to click and you can have a look at them if19 you enjoy them better. The obvious ones are ``optparse`` and ``argparse``20 from the standard library.21 22-click is actually implemented as a wrapper around a mild fork of22+Click is actually implemented as a wrapper around a mild fork of23 ``optparse`` and does not implement any parsing itself. The reason it's24 not based on ``argparse`` is that ``argparse`` does not allow proper25 nesting of commands by design and has some deficiencies when it comes to26 POSIX compliant argument handling.23 unmodified lines50 with. The reason however click is not using argparse is that it has some51 problematic behaviors that make handling arbitrary command line interfaces52 hard:53 54-* argparse has builtin magic behavior to guess if something is an54+* argparse has built-in magic behavior to guess if something is an55 argument or an option. This becomes a problem when dealing with56 incomplete command lines as it's not possible to know without having a57 full understanding of the command line how the parser is going to58 behave. This goes against click's ambitions of dispatching to13 unmodified lines72 73 Docopt for instance acts by parsing your help pages and then parsing74 according to those rules. The side effect of this is that docopt is quite75 rigid in how it handles the command line interface. The upside of docopt76-is that it gives you strong control over your help page, the downside is77-that due to that it cannot rewrap your output for the current terminal76+is that it gives you strong control over your help page; the downside is77+that due to this it cannot rewrap your output for the current terminal78 width and it makes translations hard. On top of that docopt is restricted79 to basic parsing. It does not handle argument dispatching and callback80 invocation or types. This means there is a lot of code that needs to be81 written in addition to the basic help page to handle the parsing results.82 83-Most of all however it makes composability hard. While docopt does83+Most of all, however, it makes composability hard. While docopt does84 support dispatching to subcommands, it for instance does not directly85 support any kind of automatic subcommand enumeration based on what's86 available or it does not enforce subcommands to work in a consistent way.87 88 This is fine, but it's different from how click wants to work. Click aims89 to support fully composable command line user interfaces by doing this:90 91-- click does not just parse, it also dispatches to the appropriate code.92-- click has a strong concept of an invocation context that allows91+- Click does not just parse, it also dispatches to the appropriate code.92+- Click has a strong concept of an invocation context that allows93 subcommands to respond to data from the parent command.94-- click has strong information available for all parameters and commands94+- Click has strong information available for all parameters and commands95 so that it can generate unified help pages for the full CLI and to96 assist the user in converting the input data as necessary.97-- click has strong understanding of what types are and can give the user97+- Click has a strong understanding of what types are and can give the user98 consistent error messages if something goes wrong. A subcommand99 written by a different developer will not suddenly die with a100 different error messsage because it's manually handled.101-- click has enough meta information available for its whole program101+- Click has enough meta information available for its whole program102 that it can evolve over time to improve the user experience without103- forcing developers to adjust their programs. For instance if click103+ forcing developers to adjust their programs. For instance, if click104 decides to change how help pages are formatted, all click programs105 will automatically benefit from this.106 107 The aim of click is to make composable systems, whereas the aim of docopt13 unmodified lines121 it hard to achieve a consistent command line experience.122 123 The best example for this is optparse's ``callback`` functionality for124 accepting arbitrary number of arguments. Due to syntactical ambiguities125-on the command line there is no way to implement fully variadic arguments.125+on the command line, there is no way to implement fully variadic arguments.126 There are always tradeoffs that need to be made and in case of127 ``argparse`` these tradeoffs have been critical enough, that a system like128 click cannot even be implemented on top of it.129 9 unmodified lines139 even optparse and argparse support automatic expansion of long arguments.140 The reason for this is that it's a liability for backwards compatibility.141 If people start relying on automatically modified parameters and someone142 adds a new parameter in the future, the script might stop working. These143-kind of problems are hard to find so click does not attempt to be magical143+kinds of problems are hard to find so click does not attempt to be magical144 about this.145 146 This sort of behavior however can be implemented on a higher level to147 support things such as explicit aliases. For more information see1 unmodified line