Merge pull request #2107 from pallets/path-dash-docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
`open_file` handles `pathlib.Path("-")`
authored by David Lord · committed by GitHub · parents 41f5b7a, 99bf3cc · Browse files · 6 files·+70 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+70 added−39 removed
- tests:+18 added−2 removed
- other:+52 added−37 removed
Provenance
- Commit
e415d3a- Tree
bcbc056- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
41f5b7a- Parent 2
99bf3cc
6 files changed+70 added−39 removed
modified:src/click/_compat.py+3 added-3 removed
386 unmodified lines387 atomic: bool = False,388 ) -> t.Tuple[t.IO, bool]:389 binary = "b" in mode390 391- # Standard streams first. These are simple because they don't need392- # special handling for the atomic flag. It's entirely ignored.393- if filename == "-":391+ # Standard streams first. These are simple because they ignore the392+ # atomic flag. Use fsdecode to handle Path("-").393+ if os.fsdecode(filename) == "-":394 if any(m in mode for m in ["w", "a", "x"]):395 if binary:396 return get_binary_stdout(), False397 return get_text_stdout(encoding=encoding, errors=errors), False230 unmodified linesmodified:src/click/types.py+16 added-19 removed
742 unmodified lines743 return [CompletionItem(incomplete, type="file")]744 745 746 class Path(ParamType):747- """The path type is similar to the :class:`File` type but it performs748- different checks. First of all, instead of returning an open file749- handle it returns just the filename. Secondly, it can perform various750- basic checks about what the file or directory should be.747+ """The ``Path`` type is similar to the :class:`File` type, but748+ returns the filename instead of an open file. Various checks can be749+ enabled to validate the type of file and permissions.750 752- :param exists: if set to true, the file or directory needs to exist for753- this value to be valid. If this is not required and a754- file does indeed not exist, then all further checks are755- silently skipped.756- :param file_okay: controls if a file is a possible value.757- :param dir_okay: controls if a directory is a possible value.758- :param writable: if true, a writable check is performed.759- :param readable: if true, a readable check is performed.760- :param resolve_path: if this is true, then the path is fully resolved761- before the value is passed onwards. This means762- that it's absolute and symlinks are resolved. It763- will not expand a tilde-prefix, as this is764- supposed to be done by the shell only.765- :param allow_dash: If this is set to `True`, a single dash to indicate766- standard streams is permitted.751+ :param exists: The file or directory needs to exist for the value to752+ be valid. If this is not set to ``True``, and the file does not753+ exist, then all further checks are silently skipped.754+ :param file_okay: Allow a file as a value value.755+ :param dir_okay: Allow a directory as a value.756+ :param writable: The file or directory must be writable.757+ :param readable: The file or directory must be readable.758+ :param resolve_path: Make the value absolute and resolve any759+ symlinks. A ``~`` is not expanded, as this is supposed to be760+ done by the shell only.761+ :param allow_dash: Allow a single dash as a value, which indicates762+ a standard stream (but does not open it). Use763+ :func:`~click.open_file` to handle opening this value.764 :param path_type: Convert the incoming path value to this type. If765 ``None``, keep Python's default, which is ``str``. Useful to766 convert to :class:`pathlib.Path`.767 282 unmodified linesmodified:src/click/utils.py+24 added-15 removed
338 unmodified lines339 errors: t.Optional[str] = "strict",340 lazy: bool = False,341 atomic: bool = False,342 ) -> t.IO:343- """This is similar to how the :class:`File` works but for manual344- usage. Files are opened non lazy by default. This can open regular345- files as well as stdin/stdout if ``'-'`` is passed.343+ """Open a file, with extra behavior to handle ``'-'`` to indicate344+ a standard stream, lazy open on write, and atomic write. Similar to345+ the behavior of the :class:`~click.File` param type.346 347- If stdin/stdout is returned the stream is wrapped so that the context348- manager will not close the stream accidentally. This makes it possible349- to always use the function like this without having to worry to350- accidentally close a standard stream::347+ If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is348+ wrapped so that using it in a context manager will not close it.349+ This makes it possible to use the function without accidentally350+ closing a standard stream:351 352+ .. code-block:: python353+354 with open_file(filename) as f:355 ...356 355- .. versionadded:: 3.0357+ :param filename: The name of the file to open, or ``'-'`` for358+ ``stdin``/``stdout``.359+ :param mode: The mode in which to open the file.360+ :param encoding: The encoding to decode or encode a file opened in361+ text mode.362+ :param errors: The error handling mode.363+ :param lazy: Wait to open the file until it is accessed. For read364+ mode, the file is temporarily opened to raise access errors365+ early, then closed until it is read again.366+ :param atomic: Write to a temporary file and replace the given file367+ on close.368 357- :param filename: the name of the file to open (or ``'-'`` for stdin/stdout).358- :param mode: the mode in which to open the file.359- :param encoding: the encoding to use.360- :param errors: the error handling for this file.361- :param lazy: can be flipped to true to open the file lazily.362- :param atomic: in atomic mode writes go into a temporary file and it's363- moved on close.369+ .. versionadded:: 3.0370 """371 if lazy:372 return t.cast(t.IO, LazyFile(filename, mode, encoding, errors, atomic=atomic))373+374 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)375+376 if not should_close:377 f = t.cast(t.IO, KeepOpenFile(f))378+379 return f380 381 382 def get_os_args() -> t.Sequence[str]:206 unmodified linesmodified:tests/test_arguments.py+2 added-2 removed
118 unmodified lines119 assert result.output == "Hey!"120 assert result.exit_code == 0121 122 123-def test_path_args(runner):123+def test_path_allow_dash(runner):124 @click.command()125- @click.argument("input", type=click.Path(dir_okay=False, allow_dash=True))125+ @click.argument("input", type=click.Path(allow_dash=True))126 def foo(input):127 click.echo(input)128 129 result = runner.invoke(foo, ["-"])250 unmodified linesmodified:tests/test_utils.py+16 added
318 unmodified lines319 assert result.exception is None320 assert result.output == "foobar\nmeep\n"321 322 323+def test_open_file_pathlib_dash(runner):324+ @click.command()325+ @click.argument(326+ "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)327+ )328+ def cli(filename):329+ click.echo(str(type(filename)))330+331+ with click.open_file(filename) as f:332+ click.echo(f.read())333+334+ result = runner.invoke(cli, ["-"], input="value")335+ assert result.exception is None336+ assert result.output == "pathlib.Path\nvalue\n"337+338+339 def test_open_file_ignore_errors_stdin(runner):340 @click.command()341 @click.argument("filename")342 def cli(filename):164 unmodified linesmodified:CHANGES.rst+9 added
1 .. currentmodule:: click2 3+Version 8.0.44+-------------5+6+Unreleased7+8+- ``open_file`` recognizes ``Path("-")`` as a standard stream, the9+ same as the string ``"-"``. :issue:`2106`10+11+12 Version 8.0.313 -------------14 15 Released 2021-10-10928 unmodified lines