Skip to content

Commit affd0e6

Browse files
committed
Added relpath2 function that uses pathlib in place of os.path
1 parent 1b2618c commit affd0e6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

domdf_python_tools/paths.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
#
3838

3939
import os
40+
import pathlib
4041

4142
def copytree(src, dst, symlinks=False, ignore=None):
4243
"""
@@ -115,6 +116,39 @@ def relpath(path, relative_to=None):
115116
return os.path.abspath(path)
116117

117118

119+
def relpath2(path, relative_to=None):
120+
"""
121+
Returns the path for the given file or directory relative to the given
122+
directory or, if that would require path traversal, returns the
123+
absolute path.
124+
125+
:param path: Path to find the relative path for
126+
:type path: str or pathlib.Path
127+
:param relative_to: The directory to find the path relative to.
128+
Defaults to the current directory
129+
:type relative_to: str or pathlib.Path
130+
131+
:return:
132+
"""
133+
134+
if not isinstance(path, pathlib.Path):
135+
path = pathlib.Path(path)
136+
137+
abs_path = path.absolute()
138+
139+
if relative_to is None:
140+
relative_to = pathlib.Path().absolute()
141+
142+
if not isinstance(relative_to, pathlib.Path):
143+
relative_to = pathlib.Path(relative_to)
144+
145+
relative_to = relative_to.absolute()
146+
147+
try:
148+
return abs_path.relative_to(relative_to)
149+
except ValueError:
150+
return abs_path
151+
118152

119153
def delete(filename):
120154
"""

0 commit comments

Comments
 (0)