John Lam 1997 — 2026

Hard links and the GAC

While I was at Microsoft this week, Andrew Grealy put an interesting idea in my head: using NTFS hard links to emulate some of the functionality of the GAC. The scenario that I had in mind was to create NTFS hard links to duplicate private assemblies so that I could update the “shared” private assembly simply by replacing a single file on the user’s hard drive.

On the plane ride home, I wrote a simple Python script to do just that. It looks for duplicate files on your hard disk, and moves a single copy of that file to a special place that we call the YAC (Yet Another Cache). It then replaces all copies of that file with a hard link that points to the YAC entry for that file.

It calculates MD5 hashes to ensure that duplicate files are in fact duplicates, and uses the Python Win32 extensions to call the Windows CreateHardLink API.

I absolutely love the use of Python Generators in the GetFiles method. This is such a low-friction language!

import os
import shutil
import md5
import win32file

class HardLink:
    BLOCKSIZE   = 1024
    YAC         = r'c:\dev\python\yac'

    def __init__(self):
        self.files = dict()

    def GetFiles(self, path):
        for root, dirs, files in os.walk(path):
            for file in files:
                yield root + '\\' + file

    def CalculateHash(self, path):
        f = file(path,'rb')
        m = md5.new()
        readBytes = HardLink.BLOCKSIZE
        while (readBytes):
            readString = f.read(readBytes)
            m.update(readString)
            readBytes = len(readString)
        f.close();
        return m.hexdigest()

    def GetYacPath(self, path):
        (dir, filename) = os.path.split(path)
        return HardLink.YAC + '\\' + filename

    def CreateFirstFileHardLink(self, path):
        yacPath = self.GetYacPath(path)
        shutil.move(path, yacPath)
        win32file.CreateHardLink(path, yacPath)

    def CreateNthFileHardLink(self, path):
        yacPath = self.GetYacPath(path)
        os.remove(path)
        win32file.CreateHardLink(path, yacPath)

    def Run(self, path):
        for path in self.GetFiles(path):
            hash = self.CalculateHash(path)
            if self.files.has_key(hash):
                (firstPath, flag) = self.files[hash]
                if not flag:
                    self.files[hash] = (None, True)
                    self.CreateFirstFileHardLink(firstPath)
                self.CreateNthFileHardLink(path)
            else:
                self.files[hash] = (path, False)

h = HardLink()
h.Run(r'c:\test')