1 | n/a | #! /usr/bin/env python3 |
---|
2 | n/a | |
---|
3 | n/a | # mkreal |
---|
4 | n/a | # |
---|
5 | n/a | # turn a symlink to a directory into a real directory |
---|
6 | n/a | |
---|
7 | n/a | import sys |
---|
8 | n/a | import os |
---|
9 | n/a | from stat import * |
---|
10 | n/a | |
---|
11 | n/a | join = os.path.join |
---|
12 | n/a | |
---|
13 | n/a | error = 'mkreal error' |
---|
14 | n/a | |
---|
15 | n/a | BUFSIZE = 32*1024 |
---|
16 | n/a | |
---|
17 | n/a | def mkrealfile(name): |
---|
18 | n/a | st = os.stat(name) # Get the mode |
---|
19 | n/a | mode = S_IMODE(st[ST_MODE]) |
---|
20 | n/a | linkto = os.readlink(name) # Make sure again it's a symlink |
---|
21 | n/a | f_in = open(name, 'r') # This ensures it's a file |
---|
22 | n/a | os.unlink(name) |
---|
23 | n/a | f_out = open(name, 'w') |
---|
24 | n/a | while 1: |
---|
25 | n/a | buf = f_in.read(BUFSIZE) |
---|
26 | n/a | if not buf: break |
---|
27 | n/a | f_out.write(buf) |
---|
28 | n/a | del f_out # Flush data to disk before changing mode |
---|
29 | n/a | os.chmod(name, mode) |
---|
30 | n/a | |
---|
31 | n/a | def mkrealdir(name): |
---|
32 | n/a | st = os.stat(name) # Get the mode |
---|
33 | n/a | mode = S_IMODE(st[ST_MODE]) |
---|
34 | n/a | linkto = os.readlink(name) |
---|
35 | n/a | files = os.listdir(name) |
---|
36 | n/a | os.unlink(name) |
---|
37 | n/a | os.mkdir(name, mode) |
---|
38 | n/a | os.chmod(name, mode) |
---|
39 | n/a | linkto = join(os.pardir, linkto) |
---|
40 | n/a | # |
---|
41 | n/a | for filename in files: |
---|
42 | n/a | if filename not in (os.curdir, os.pardir): |
---|
43 | n/a | os.symlink(join(linkto, filename), join(name, filename)) |
---|
44 | n/a | |
---|
45 | n/a | def main(): |
---|
46 | n/a | sys.stdout = sys.stderr |
---|
47 | n/a | progname = os.path.basename(sys.argv[0]) |
---|
48 | n/a | if progname == '-c': progname = 'mkreal' |
---|
49 | n/a | args = sys.argv[1:] |
---|
50 | n/a | if not args: |
---|
51 | n/a | print('usage:', progname, 'path ...') |
---|
52 | n/a | sys.exit(2) |
---|
53 | n/a | status = 0 |
---|
54 | n/a | for name in args: |
---|
55 | n/a | if not os.path.islink(name): |
---|
56 | n/a | print(progname+':', name+':', 'not a symlink') |
---|
57 | n/a | status = 1 |
---|
58 | n/a | else: |
---|
59 | n/a | if os.path.isdir(name): |
---|
60 | n/a | mkrealdir(name) |
---|
61 | n/a | else: |
---|
62 | n/a | mkrealfile(name) |
---|
63 | n/a | sys.exit(status) |
---|
64 | n/a | |
---|
65 | n/a | if __name__ == '__main__': |
---|
66 | n/a | main() |
---|