Merge pull request #2094 from pallets/path-resolve-symlink
Before adoption: this commit came in with the history the project adopted, so no landing records it.
use pathlib to resolve symlinks
authored by David Lord · committed by GitHub · parents 96146c9, c8ca29b · Browse files · 4 files·+47 added−61 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+47 added−61 removed
- tests:+34 added−48 removed
- other:+13 added−13 removed
Provenance
- Commit
3737511- Tree
1f61481- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
96146c9- Parent 2
c8ca29b
4 files changed+47 added−61 removed
modified:src/click/types.py+4 added-13 removed
834 unmodified lines835 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")836 837 if not is_dash:838 if self.resolve_path:839- # Get the absolute directory containing the path.840- dir_ = os.path.dirname(os.path.abspath(rv))839+ # os.path.realpath doesn't resolve symlinks on Windows840+ # until Python 3.8. Use pathlib for now.841+ import pathlib842 842- # Resolve a symlink. realpath on Windows Python < 3.9843- # doesn't resolve symlinks. This might return a relative844- # path even if the path to the link is absolute.845- if os.path.islink(rv):846- rv = os.readlink(rv)843+ rv = os.fsdecode(pathlib.Path(rv).resolve())844 848- # Join dir_ with the resolved symlink if the resolved849- # path is relative. This will make it relative to the850- # original containing directory.851- if not os.path.isabs(rv):852- rv = os.path.join(dir_, rv)853-845 try:846 st = os.stat(rv)847 except OSError:848 if not self.exists:204 unmodified linesmodified:tests/conftest.py+14 added-18 removed
1 import os2-import shutil2 import tempfile3 4 import pytest5 4 unmodified lines10 def runner(request):11 return CliRunner()12 13 15-def check_symlink_impl():16- """This function checks if using symlinks is allowed17- on the host machine"""18- tempdir = tempfile.mkdtemp(prefix="click-")19- test_pth = os.path.join(tempdir, "check_sym_impl")20- sym_pth = os.path.join(tempdir, "link")21- open(test_pth, "w").close()22- rv = True23- try:24- os.symlink(test_pth, sym_pth)25- except (NotImplementedError, OSError):26- # Creating symlinks on Windows require elevated access.27- # OSError is thrown if the function is called without it.28- rv = False29- finally:30- shutil.rmtree(tempdir, ignore_errors=True)31- return rv14+def _check_symlinks_supported():15+ with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:16+ target = os.path.join(tempdir, "target")17+ open(target, "w").close()18+ link = os.path.join(tempdir, "link")19+20+ try:21+ os.symlink(target, link)22+ return True23+ except OSError:24+ return False25+26+27+symlinks_supported = _check_symlinks_supported()modified:tests/test_types.py+20 added-30 removed
1 import os.path2 import pathlib3 4 import pytest5-from conftest import check_symlink_impl5+from conftest import symlinks_supported6 7 import click8 9 93 unmodified lines103 assert result.exception is None104 assert result.return_value == expect105 106 107-@pytest.mark.skipif(not check_symlink_impl(), reason="symlink not allowed on device")108-@pytest.mark.parametrize(109- ("sym_file", "abs_fun"),110- [111- (("relative_symlink",), os.path.basename),112- (("test", "absolute_symlink"), lambda x: x),113- ],107+@pytest.mark.skipif(108+ not symlinks_supported, reason="The current OS or FS doesn't support symlinks."109 )115-def test_symlink_resolution(tmpdir, sym_file, abs_fun):116- """This test ensures symlinks are properly resolved by click"""117- tempdir = str(tmpdir)118- real_path = os.path.join(tempdir, "test_file")119- sym_path = os.path.join(tempdir, *sym_file)110+def test_path_resolve_symlink(tmp_path, runner):111+ test_file = tmp_path / "file"112+ test_file_str = os.fsdecode(test_file)113+ test_file.write_text("")114 121- # create dirs and files122- os.makedirs(os.path.join(tempdir, "test"), exist_ok=True)123- open(real_path, "w").close()124- os.symlink(abs_fun(real_path), sym_path)115+ path_type = click.Path(resolve_path=True)116+ param = click.Argument(["a"], type=path_type)117+ ctx = click.Context(click.Command("cli", params=[param]))118 126- # test127- ctx = click.Context(click.Command("do_stuff"))128- rv = click.Path(resolve_path=True).convert(sym_path, None, ctx)119+ test_dir = tmp_path / "dir"120+ test_dir.mkdir()121 130- # os.readlink prepends path prefixes to absolute131- # links in windows.132- # https://docs.microsoft.com/en-us/windows/win32/133- # ... fileio/naming-a-file#win32-file-namespaces134- #135- # Here we strip win32 path prefix from the resolved path136- rv_drive, rv_path = os.path.splitdrive(rv)137- stripped_rv_drive = rv_drive.split(os.path.sep)[-1]138- rv = os.path.join(stripped_rv_drive, rv_path)122+ abs_link = test_dir / "abs"123+ abs_link.symlink_to(test_file)124+ abs_rv = path_type.convert(os.fsdecode(abs_link), param, ctx)125+ assert abs_rv == test_file_str126 140- assert rv == real_path127+ rel_link = test_dir / "rel"128+ rel_link.symlink_to(pathlib.Path("..") / "file")129+ rel_rv = path_type.convert(os.fsdecode(rel_link), param, ctx)130+ assert rel_rv == test_file_strmodified:CHANGES.rst+9 added
1 .. currentmodule:: click2 3+Version 8.0.34+-------------5+6+Unreleased7+8+- Fix issue with ``Path(resolve_path=True)`` type creating invalid9+ paths. :issue:`2088`10+11+12 Version 8.0.213 -------------14 15 Released 2021-10-08915 unmodified lines