Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
3-manifolds
GitHub Repository: 3-manifolds/Sage_macOS
Path: blob/main/Sage_framework/relativize_links.py
172 views
1
"""
2
Walk through the directory passed as argv[1] and convert each absolute
3
symlink into a relative symlink. Exits with status 1 and prints a warning
4
if any symlink is broken or points outside of the top level directory.
5
6
This needs to be run on the sage directory to remove absolute
7
symlinks created when installing packages (mainly GAP packages.)
8
"""
9
10
import os
11
import sys
12
13
def fix_symlinks(root_dir, check_only=False):
14
for dirpath, dirnames, filenames in os.walk(root_dir):
15
for filename in filenames + dirnames:
16
link_path = os.path.join(dirpath, filename)
17
if not os.path.islink(link_path):
18
continue
19
target = os.readlink(link_path)
20
if os.path.isabs(target):
21
if not os.path.exists(target):
22
print('%s is a broken symlink'%link_path)
23
if not check_only:
24
sys.exit(1)
25
continue
26
if not target.startswith(root_dir):
27
print('%s has a forbidden target'%link_path)
28
if not check_only:
29
sys.exit(1)
30
target_dir, target_base = os.path.split(target)
31
relative_path = os.path.relpath(dirpath, target_dir)
32
new_target = os.path.normpath(
33
os.path.join(relative_path, target_base))
34
if check_only:
35
print('Absolute link: %s -> %s\n'%(link_path, target))
36
else:
37
print('Fixed: %s -> %s'%(link_path, new_target))
38
os.remove(link_path)
39
os.symlink(new_target, link_path)
40
else:
41
full_target = os.path.join(dirpath, target)
42
if not os.path.exists(full_target):
43
print('%s is a broken symlink'%link_path)
44
if not check_only:
45
sys.exit(1)
46
47
def main():
48
try:
49
root_dir = os.path.abspath(sys.argv[1])
50
except IndexError:
51
print('Usage: relativize_links dir')
52
sys.exit(1)
53
if not os.path.isdir(root_dir):
54
print('%s is not a directory'%root_dir)
55
sys.exit(1)
56
fix_symlinks(root_dir, check_only=False)
57
58
if __name__ == '__main__':
59
main()
60
61