Skip to content
Myr

Added docs for path type

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent a6af25d · Browse files · 2 files+43 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+43 added−1 removed

  • other:+43 added−1 removed

2 files+43 added−1 removed

modified:docs/arguments.rst+42 added
56 unmodified lines
57.. click:run::5859 invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])6061Note that this is not how you would write this application. The reason62for this is that in this particular example the arguments are defined as63strings. File names however are not strings! They might be (on certain64operating systems) but not necessarily on others. For better ways see the65next sections.6667.. admonition:: Note on Non-Empty Variadic Arguments6869 If you come from ``argparse`` you might be missing support for setting70 ``nargs`` to ``+`` to indicate that at least one argument is required.
41 unmodified lines
112 invoke(inout, args=['-', 'hello.txt'], input=['hello'],113 terminate_input=True)114 invoke(inout, args=['hello.txt', '-'])115116File Path Arguments117-------------------118119In the previous example the files were opened immediately. But what if120we just want the filename? The naive way is to use the default string121argument type. However remember that click is unicode based so the string122will be a unicode value always. Filenames unfortunately however can be123unicode or bytes depending on which operating system you're on. As such124the type is insufficient.125126Instead you should be using the :class:`Path` type which handles this127complexity for you. Not only will it return either bytes or unicode128depending on what makes more sense, but it will also be able to do some129basic checks for you such as existence checks.130131Example:132133.. click:example::134135 @click.command()136 @click.argument('f', type=click.Path(exists=True))137 def touch(f):138 click.echo(click.format_filename(f))139140And what it does:141142.. click:run::143144 with isolated_filesystem():145 with open('hello.txt', 'w') as f:146 f.write('Hello World!\n')147 invoke(touch, args=['hello.txt'])148 println()149 invoke(touch, args=['missing.txt'])150151152File Opening Safety153-------------------154155The :class:`FileType` type has one problem it needs to deal with and that
87 unmodified lines
modified:examples/repo/repo.py+1 added-1 removed
105 unmodified lines
106@cli.command()107@click.option('--message', '-m', multiple=True,108 help='The commit message. If provided multiple times each '109 'argument gets converted into a new line.')110@click.argument('files', nargs=-1)110@click.argument('files', nargs=-1, type=click.Path())111@pass_repo112def commit(repo, files, message):113 """Commits outstanding changes.114
37 unmodified lines