1import sys
2import os
3import stat
4
5# Ensure that this is being run on a specific platform
6assert sys.platform.startswith('linux') or sys.platform.startswith('darwin') \
7    or sys.platform.startswith('cygwin') or sys.platform.startswith('freebsd')
8
9def env_path():
10    ep = os.environ.get('LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT')
11    assert ep is not None
12    ep = os.path.realpath(ep)
13    assert os.path.isdir(ep)
14    return ep
15
16env_path_global = env_path()
17
18# Make sure we don't try and write outside of env_path.
19# All paths used should be sanitized
20def sanitize(p):
21    p = os.path.realpath(p)
22    if os.path.commonprefix([env_path_global, p]):
23        return p
24    assert False
25
26"""
27Some of the tests restrict permissions to induce failures.
28Before we delete the test enviroment, we have to walk it and re-raise the
29permissions.
30"""
31def clean_recursive(root_p):
32    if not os.path.islink(root_p):
33        os.chmod(root_p, 0o777)
34    for ent in os.listdir(root_p):
35        p = os.path.join(root_p, ent)
36        if os.path.islink(p) or not os.path.isdir(p):
37            os.remove(p)
38        else:
39            assert os.path.isdir(p)
40            clean_recursive(p)
41            os.rmdir(p)
42
43
44def init_test_directory(root_p):
45    root_p = sanitize(root_p)
46    assert not os.path.exists(root_p)
47    os.makedirs(root_p)
48
49
50def destroy_test_directory(root_p):
51    root_p = sanitize(root_p)
52    clean_recursive(root_p)
53    os.rmdir(root_p)
54
55
56def create_file(fname, size):
57    with open(sanitize(fname), 'w') as f:
58        f.write('c' * size)
59
60
61def create_dir(dname):
62    os.mkdir(sanitize(dname))
63
64
65def create_symlink(source, link):
66    os.symlink(sanitize(source), sanitize(link))
67
68
69def create_hardlink(source, link):
70    os.link(sanitize(source), sanitize(link))
71
72
73def create_fifo(source):
74    os.mkfifo(sanitize(source))
75
76
77def create_socket(source):
78    mode = 0o600 | stat.S_IFSOCK
79    os.mknod(sanitize(source), mode)
80
81
82if __name__ == '__main__':
83    command = " ".join(sys.argv[1:])
84    eval(command)
85    sys.exit(0)
86