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