app/django/utils/_os.py
changeset 54 03e267d67478
child 323 ff1a9aa48cfd
equal deleted inserted replaced
53:57b4279d8c4e 54:03e267d67478
       
     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