-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsufs.py
executable file
·206 lines (159 loc) · 5.58 KB
/
sufs.py
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env python3
from fnmatch import fnmatch
from pathlib import Path
import sys
import os
from os.path import lexists
from typing import List, Dict, Optional
from subprocess import check_call
# indicates that the directory is managed by sufs
# TODO later, link back to the sources as well?
_MARKER = '.symlinkfs'
def run(from_: List[Path], to: Path, ignore: Optional[List[str]]=None):
assert len(from_) > 0
assert to.resolve().is_dir(), to
def matches(p: Path) -> bool:
if ignore is None:
return True
else:
ignored = any(fnmatch(p.name, ii) for ii in ignore)
return not ignored
# TODO maybe, have init method??
existing = list(to.iterdir())
for p in existing:
if p.name != _MARKER:
assert p.is_symlink(), p
# TODO not sure about is_dir here
sets = [set(x for x in p.iterdir() if x.is_dir() and matches(x)) for p in from_]
spec: Dict[str, Path] = {}
errors = False
for s in sets:
for src in s:
name = src.name
if name in spec:
print(f"Clashing path: {spec[name]}, {src}", file=sys.stderr)
errors = True
else:
spec[name] = src
assert not errors, 'Clashing names detected!'
# check_call(['stat', str(to)])
# assert not os.access(str(to), os.W_OK)
# ugh. no nice method in python to remove permission...
check_call(['chmod', 'u+w', str(to)])
try:
# remove old broken links which point to from_
for p in existing:
if p.exists():
continue
points_to = Path(os.readlink(p))
for src in from_:
try:
points_to.relative_to(src)
print(f'unlinking broken link {p}', file=sys.stderr)
p.unlink()
break
except ValueError:
continue
# link new stuff
for name, src in spec.items():
old = to / name
if lexists(old):
old_src = Path(os.readlink(old))
if old_src == src:
print(f"skipping {old}, no need to update", file=sys.stderr)
continue
else:
old.unlink()
print(f"linking {old} -> {src}", file=sys.stderr)
old.symlink_to(src)
(to / _MARKER).mkdir(exist_ok=True)
finally:
check_call(['chmod', 'ugo-w', str(to)])
def main():
import argparse
p = argparse.ArgumentParser()
p.add_argument('--to', type=Path, required=True)
p.add_argument('--ignore', type=str, action='append', help="Glob to ignore certain subdirectories (e.g. .dropbox.cache if you're using Dropbox)", required=False)
p.add_argument('sources', type=Path, nargs='+')
# TODO inotify and run as systemd service?
# TODO what to do with broken symliks?
# TODO assert no regular files
args = p.parse_args()
run(from_=args.sources, to=args.to, ignore=args.ignore)
def test_nonexistent(tmp_path: Path) -> None:
import pytest # type: ignore
with pytest.raises(Exception): # due to nonexistent target dir
run(from_=[tmp_path / 'c1', tmp_path / 'c2'], to=tmp_path / 'nosuchdir')
def test(tmp_path: Path) -> None:
merged = tmp_path / 'merged'
merged.mkdir()
_test_helper(tdir=tmp_path, merged=merged)
def test_symlink(tmp_path: Path) -> None:
merged = tmp_path / 'merged'
merged.mkdir()
link = tmp_path / 'link'
link.symlink_to(merged)
_test_helper(tdir=tmp_path, merged=link)
def _test_helper(tdir: Path, merged: Path) -> None:
import pytest # type: ignore
c1 = tdir / 'c1'
aaa1 = c1 / 'aaa'
bbb = c1 / 'bbb'
c2 = tdir / 'c2'
aaa2 = c2 / 'aaa'
ccc = c2 / 'ccc'
c3 = tdir / 'c3'
zzz = c3 / 'zzz'
for d in [aaa1, bbb, aaa2, ccc, zzz]:
d.mkdir(exist_ok=True, parents=True)
fff = c1 / 'file'
fff.touch()
# TODO maybe, return filenames instead?
def get():
res = set(merged.iterdir())
mrk = merged / _MARKER
assert mrk in res
res.remove(mrk)
return res
run(from_=[c1], to=merged)
assert get() == {
merged / 'aaa',
merged / 'bbb',
}
# should set proper permissions after
with pytest.raises(PermissionError):
(merged / 'alalala').touch()
run(from_=[c1, c3], to=merged)
assert get() == {
merged / 'aaa',
merged / 'bbb',
merged / 'zzz',
}
zzz.rmdir()
run(from_=[c1], to=merged)
# zzz link stays regardless being deleted because it didn't point to any of source directories
assert get() == {
merged / 'aaa',
merged / 'bbb',
merged / 'zzz',
}
run(from_=[c1, c3], to=merged)
# zzz goes now because in points to c3 which is managed
assert get() == {merged / 'aaa', merged / 'bbb'}
with pytest.raises(Exception): # due to duplicate file 'aaa'
run(from_=[c1, c2], to=merged)
assert get() == {merged / 'aaa', merged / 'bbb'} # shouldn't change anything
# TODO marker file?
aaa1.rmdir()
run(from_=[c1, c2], to=merged)
assert get() == {merged / 'aaa', merged / 'bbb', merged / 'ccc'}
run(from_=[c1, c2], to=merged)
assert get() == {merged / 'aaa', merged / 'bbb', merged / 'ccc'}
eee = c1 / 'eee'
eee.mkdir()
run(from_=[c1, c2], to=merged)
assert get() == {merged / 'aaa', merged / 'bbb', merged / 'ccc', merged / 'eee'}
if __name__ == '__main__':
# TODO assert all exist first?
# TODO ok link and error? not sure..
main()