Implemented the 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 f353cf1 · Browse files · 5 files·+137 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+137 added−4 removed
- tests:+49 added−0 removed
- other:+88 added−4 removed
Provenance
- Commit
2e7c39c- Tree
198c3ff- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f353cf1
5 files changed+137 added−4 removed
modified:click/__init__.py+4 added-4 removed
22 unmodified lines23 command, group, argument, option, confirmation_option, \24 password_option, version_option, help_option25 26 # Types27-from .types import ParamType, File, Choice, IntRange, STRING, INT, FLOAT, \28- BOOL, UUID27+from .types import ParamType, File, Path, Choice, IntRange, STRING, INT, \28+ FLOAT, BOOL, UUID29 30 # Utilities31 from .utils import echo32 20 unmodified lines53 'argument', 'option', 'confirmation_option', 'password_option',54 'version_option', 'help_option',55 56 # Types57- 'ParamType', 'File', 'Choice', 'IntRange', 'STRING', 'INT', 'FLOAT',58- 'BOOL', 'UUID',57+ 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'STRING', 'INT',58+ 'FLOAT', 'BOOL', 'UUID',59 60 # Utilities61 'echo',62 12 unmodified linesmodified:click/types.py+79 added
1+import os2 import sys3+import stat4 import uuid5 6 from ._compat import open_stream, text_type, filename_to_ui, get_streerror7 from .exceptions import UsageError264 unmodified lines272 get_streerror(e),273 ), param, ctx)274 275 276+class Path(ParamType):277+ """The path type is similar to the :class:`File` type but it performs278+ different checks. First of all, instead of returning a open file279+ handle it returns just the filename. Secondly it can perform various280+ basic checks about what the file or directory should be.281+282+ :param exists: if set to true, the file or directory needs to exist for283+ this value to be valid. If this is not required and a284+ file does indeed not exist, then all further checks are285+ silently skipped.286+ :param file_okay: controls if a file is a possible value.287+ :param dir_okay: controls if a directory is a possible value.288+ :param writable: if true, the a writable check is performed.289+ :param readable: if true, the a readable check is performed.290+ :param resolve_path: if this is true, then the path is fully resolved291+ before the value is passed onwards. This means292+ that it's absolute and symlinks are resolved.293+ """294+295+ def __init__(self, exists=False, file_okay=True, dir_okay=True,296+ writable=False, readable=True, resolve_path=False):297+ self.exists = exists298+ self.file_okay = file_okay299+ self.dir_okay = dir_okay300+ self.writable = writable301+ self.readable = readable302+ self.resolve_path = resolve_path303+304+ if self.file_okay and not self.dir_okay:305+ self.name = 'file'306+ self.path_type = 'File'307+ if self.dir_okay and not self.file_okay:308+ self.name = 'directory'309+ self.path_type = 'Directory'310+ else:311+ self.name = 'path'312+ self.path_type = 'Path'313+314+ def convert(self, value, param, ctx):315+ rv = value316+ if self.resolve_path:317+ rv = os.path.realpath(rv)318+319+ try:320+ st = os.stat(rv)321+ except OSError:322+ if not self.exists:323+ return rv324+ self.fail('%s "%s" does not exist.' % (325+ self.path_type,326+ filename_to_ui(value)327+ ))328+329+ if not self.file_okay and stat.S_ISREG(st.st_mode):330+ self.fail('%s "%s" is a file.' % (331+ self.path_type,332+ filename_to_ui(value)333+ ))334+ if not self.dir_okay and stat.S_ISDIR(st.st_mode):335+ self.fail('%s "%s" is a directory.' % (336+ self.path_type,337+ filename_to_ui(value)338+ ))339+ if self.writable and not os.access(value, os.W_OK):340+ self.fail('%s "%s" is not writable.' % (341+ self.path_type,342+ filename_to_ui(value)343+ ))344+ if self.readable and not os.access(value, os.R_OK):345+ self.fail('%s "%s" is not readable.' % (346+ self.path_type,347+ filename_to_ui(value)348+ ))349+350+ return rv351+352+353 def convert_type(ty, default=None):354 """Converts a callable or python ty into the most appropriate param355 ty.356 """41 unmodified linesmodified:docs/api.rst+2 added
88 unmodified lines89 .. autodata:: UUID90 91 .. autoclass:: File92 93+.. autoclass:: Path94+95 .. autoclass:: Choice96 97 .. autoclass:: IntRange98 26 unmodified linesmodified:docs/parameters.rst+3 added
56 unmodified lines57 58 .. autoclass:: File59 :noindex:60 61+.. autoclass:: Path62+ :noindex:63+64 .. autoclass:: Choice65 :noindex:66 67 .. autoclass:: IntRange53 unmodified linesmodified:tests/test_basic.py+49 added
229 unmodified lines230 assert 'Invalid value for "--file": Could not open file: example.txt' \231 in result_in.output232 233 234+def test_path_option(runner):235+ @click.command()236+ @click.option('-O', type=click.Path(file_okay=False, exists=True,237+ writable=True))238+ def write_to_dir(o):239+ with open(os.path.join(o, 'foo.txt'), 'wb') as f:240+ f.write(b'meh\n')241+242+ with runner.isolated_filesystem():243+ os.mkdir('test')244+245+ result = runner.invoke(write_to_dir, ['-O', 'test'])246+ assert not result.exception247+248+ with open('test/foo.txt', 'rb') as f:249+ assert f.read() == b'meh\n'250+251+ result = runner.invoke(write_to_dir, ['-O', 'test/foo.txt'])252+ assert 'Invalid value: Directory "test/foo.txt" is a file.' \253+ in result.output254+255+ @click.command()256+ @click.option('-f', type=click.Path(exists=True))257+ def showtype(f):258+ click.echo('is_file=%s' % os.path.isfile(f))259+ click.echo('is_dir=%s' % os.path.isdir(f))260+261+ with runner.isolated_filesystem():262+ result = runner.invoke(showtype, ['-f', 'xxx'])263+ assert 'Error: Invalid value: Path "xxx" does not exist' \264+ in result.output265+266+ result = runner.invoke(showtype, ['-f', '.'])267+ assert 'is_file=False' in result.output268+ assert 'is_dir=True' in result.output269+270+ @click.command()271+ @click.option('-f', type=click.Path())272+ def exists(f):273+ click.echo('exists=%s' % os.path.exists(f))274+275+ with runner.isolated_filesystem():276+ result = runner.invoke(exists, ['-f', 'xxx'])277+ assert 'exists=False' in result.output278+279+ result = runner.invoke(exists, ['-f', '.'])280+ assert 'exists=True' in result.output281+282+283 def test_choice_option(runner):284 @click.command()285 @click.option('--method', type=click.Choice(['foo', 'bar', 'baz']))286 def cli(method):102 unmodified lines