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