Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/utils/_os.py: 38%
28 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1import os
2import tempfile
3from os.path import abspath, dirname, join, normcase, sep
4from pathlib import Path
6from django.core.exceptions import SuspiciousFileOperation
9def safe_join(base, *paths):
10 """
11 Join one or more path components to the base path component intelligently.
12 Return a normalized, absolute version of the final path.
14 Raise ValueError if the final path isn't located inside of the base path
15 component.
16 """
17 final_path = abspath(join(base, *paths))
18 base_path = abspath(base)
19 # Ensure final_path starts with base_path (using normcase to ensure we
20 # don't false-negative on case insensitive operating systems like Windows),
21 # further, one of the following conditions must be true:
22 # a) The next character is the path separator (to prevent conditions like
23 # safe_join("/dir", "/../d"))
24 # b) The final path must be the same as the base path.
25 # c) The base path must be the most root path (meaning either "/" or "C:\\")
26 if ( 26 ↛ 31line 26 didn't jump to line 31
27 not normcase(final_path).startswith(normcase(base_path + sep))
28 and normcase(final_path) != normcase(base_path)
29 and dirname(normcase(base_path)) != normcase(base_path)
30 ):
31 raise SuspiciousFileOperation(
32 "The joined path ({}) is located outside of the base path "
33 "component ({})".format(final_path, base_path)
34 )
35 return final_path
38def symlinks_supported():
39 """
40 Return whether or not creating symlinks are supported in the host platform
41 and/or if they are allowed to be created (e.g. on Windows it requires admin
42 permissions).
43 """
44 with tempfile.TemporaryDirectory() as temp_dir:
45 original_path = os.path.join(temp_dir, "original")
46 symlink_path = os.path.join(temp_dir, "symlink")
47 os.makedirs(original_path)
48 try:
49 os.symlink(original_path, symlink_path)
50 supported = True
51 except (OSError, NotImplementedError):
52 supported = False
53 return supported
56def to_path(value):
57 """Convert value to a pathlib.Path instance, if not already a Path."""
58 if isinstance(value, Path):
59 return value
60 elif not isinstance(value, str):
61 raise TypeError("Invalid path type: %s" % type(value).__name__)
62 return Path(value)