1#! /usr/bin/env python3 2 3# mkreal 4# 5# turn a symlink to a directory into a real directory 6 7import sys 8import os 9from stat import * 10 11join = os.path.join 12 13error = 'mkreal error' 14 15BUFSIZE = 32*1024 16 17def 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 30def 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 44def 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 64if __name__ == '__main__': 65 main() 66