remove_pardir_symbols()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 15
rs 9.4285
1
# coding=utf-8
2
"""
3
"""
4
__author__ = 'Alisue <[email protected]>'
5
import os
6
7
8
def url_to_filename(url):
9
    """
10
    Safely translate url to relative filename
11
12
    Args:
13
        url (str): A target url string
14
15
    Returns:
16
        str
17
    """
18
    # remove leading/trailing slash
19
    if url.startswith('/'):
20
        url = url[1:]
21
    if url.endswith('/'):
22
        url = url[:-1]
23
    # remove pardir symbols to prevent unwilling filesystem access
24
    url = remove_pardir_symbols(url)
25
    # replace dots to underscore in filename part
26
    url = replace_dots_to_underscores_at_last(url)
27
    return url
28
29
30
def remove_pardir_symbols(path, sep=os.sep, pardir=os.pardir):
31
    """
32
    Remove relative path symobls such as '..'
33
34
    Args:
35
        path (str): A target path string
36
        sep (str): A strint to refer path delimiter (Default: `os.sep`)
37
        pardir (str): A string to refer parent directory (Default: `os.pardir`)
38
39
    Returns:
40
        str
41
    """
42
    bits = path.split(sep)
43
    bits = (x for x in bits if x != pardir)
44
    return sep.join(bits)
45
46
47
def replace_dots_to_underscores_at_last(path):
48
    """
49
    Remove dot ('.') while a dot is treated as a special character in backends
50
51
    Args:
52
        path (str): A target path string
53
54
    Returns:
55
        str
56
    """
57
    if path == '':
58
        return path
59
    bits = path.split('/')
60
    bits[-1] = bits[-1].replace('.', '_')
61
    return '/'.join(bits)
62
63
64
if __name__ == '__main__':
65
    import doctest
66
    doctest.testmod()
67