22.7. Using a Custom CacheDir Class

You can customize the behavior of derived-file caching to add your own features, for example to support compressed and/or encrypted cache files, modify cache file permissions to better support shared caches, gather additional statistics and data, etc.

To define custom cache behavior, subclass the SCons.CacheDir.CacheDir class, specializing those methods you want to change. You can pass this custom class as the custom_class parameter when calling CacheDir for global reach, or when calling env.CacheDir for a specific environment. You can also set the construction variable $CACHEDIR_CLASS to the custom class - this needs to happen before configuring the cache in that environment. SCons will internally invoke and use your custom class when performing cache operations. The below example shows a simple use case of overriding the copy_from_cache method to record the total number of bytes pulled from the cache.

import os
import SCons.CacheDir

class CustomCacheDir(SCons.CacheDir.CacheDir):
    total_retrieved = 0

    @classmethod
    def copy_from_cache(cls, env, src, dst):
        # record total bytes pulled from cache
        cls.total_retrieved += os.stat(src).st_size
        return super().copy_from_cache(env, src, dst)

env = Environment()
env.CacheDir('scons-cache', custom_class=CustomCacheDir)
# ...