ref: 667a455c46e25be1dcfd42d86e3d9c26e86e96d6 fixnamespaces/__main__.py -rwxr-xr-x 1.9 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#! env python3

import sys, os

examples = [
    "new \\Namespace\\SomethingElse",
    "\\Other\\Namespace\Class::method",
    '"\\nQuoted"',
    "\\App\\UserLookup::find('derp')",
    "\\App\\UserLookup::find('derp2')",
]

def is_line_namespaced(line: str) -> bool:
    if "\\" in line:
        return True
    return False

def is_slash_quoted(line: str) -> bool:

    first_slash = line.find("\\")
    first_quote = line.find('"')
    closing_quote = line.find('"', first_quote+1)

    if first_quote < first_slash < closing_quote:
        return True
    return False

def has_use(line: str) -> bool:
    if 'use' in line:
        return True
    return False

def extract_namespace(line: str) -> list:

    elements = line[line.find("\\"):].split("\\")
    org_class_element = elements[-1:][0]

    if '::' in org_class_element:
        class_element = org_class_element.split('::')[0]
    else:
        class_element = org_class_element

    elements[len(elements)-1] = class_element

    return("\\".join(elements), org_class_element)


def test_bool_call(func, param):
    if func(param):
        print("{} {} is OK".format(func, param))
    else:
        print("{} {} is BAD".format(func, param))

def return_import_statements(classes: set) -> str:
    use = "// automagically fixed\n"
    for c in classes:
        use += "use {};\n".format(c)
    return use


def main(file_path: str):

    namespaces = []
    with open(file_path, 'r') as f:
        for line in f.readlines():
            if is_line_namespaced(line) and not is_slash_quoted(line) and has_use(line):
                path, class_element = extract_namespace(line)
                namespaces.append(path)
                print("{}\n{}".format(line, line.replace(path[:-1], "").replace("\\", "")))

    print(set(namespaces))
    print(return_import_statements(set(namespaces)))

if len(sys.argv) == 2:
    main(sys.argv[1])