equal
deleted
inserted
replaced
|
1 from os.path import join, normcase, abspath, sep |
|
2 |
|
3 def safe_join(base, *paths): |
|
4 """ |
|
5 Joins one or more path components to the base path component intelligently. |
|
6 Returns a normalized, absolute version of the final path. |
|
7 |
|
8 The final path must be located inside of the base path component (otherwise |
|
9 a ValueError is raised). |
|
10 """ |
|
11 # We need to use normcase to ensure we don't false-negative on case |
|
12 # insensitive operating systems (like Windows). |
|
13 final_path = normcase(abspath(join(base, *paths))) |
|
14 base_path = normcase(abspath(base)) |
|
15 base_path_len = len(base_path) |
|
16 # Ensure final_path starts with base_path and that the next character after |
|
17 # the final path is os.sep (or nothing, in which case final_path must be |
|
18 # equal to base_path). |
|
19 if not final_path.startswith(base_path) \ |
|
20 or final_path[base_path_len:base_path_len+1] not in ('', sep): |
|
21 raise ValueError('the joined path is located outside of the base path' |
|
22 ' component') |
|
23 return final_path |