Yi's Blog

思绪来得快,去得也快

Fix Soft Links in an Archived File

OS X 10.8 sdk was not included in Xcode 6.1, so if you want to use that sdk, you have to add it to /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/ yourself. For me, the reason I needed 10.8 sdk was I wanted to compile objc runtime source code with it so I can debug the code.

How to get the previous sdks

You can extract previous sdks from old versions fo Xcode. Or you can get them more efficently from this repository(phracker/MacOSX-SDKs) by using git or just downloading the zip file.

But if you choose downloading the zip file, the zip format will break all the soft link by changing them into plain text files.

How to fix it

In order to fix it, I wrote several lines of python. Here is the code:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Jeswang<wangyi724@gmail.com>
#         http://blog.jeswang.org
# Created on 2014-10-22 13:03:12

import os

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError:
        return False

def folder_exists(foldername):
    try:
        os.walk(foldername).next()
        return True
    except StopIteration:
        return False

def generateSoftLink(realfile, linkfile):
    print("%s -> %s" % (linkfile, realfile))
    os.symlink(realfile, linkfile)

def generateSoftLinkForPath(path):
    list_of_files = {}
    for (dirpath, dirnames, filenames) in os.walk(path):
        for filename in filenames:
            print filename
            linkfile = dirpath+"/"+filename

            if os.path.islink(linkfile) or os.path.getsize(linkfile) > 200:
                continue

            f = open(linkfile)
            relpath = f.readline()
            f.close()

            if len(relpath) == 0:
                continue

            relpath = relpath.replace("\n", "")

            if len(relpath.replace("/", "")) == 0:
                continue

            realfile = dirpath+"/"+relpath

            if file_exists(realfile) or folder_exists(realfile):
                os.remove(linkfile)
                generateSoftLink(relpath, linkfile)

if __name__ == "__main__":
    generateSoftLinkForPath("/Users/jeswang/Downloads/MacOSX-SDKs-master")

The tricky part is, under mac os x python’s function os.path.exists can’t deal well with soft links, so you have to test whether there is a file or folder in given path by trying to read the file or list the folder.

Because of the recursion of references, you may need to run this script several time to make sure all the soft link have be changed back.

- EOF -