Search code examples
scons

How do I filter an SCons Glob result?


I sometimes want to exclude certain source files from a Glob result in SCons. Usually it's because I want to compile that source file with different options. Something like this:

objs = env.Object(Glob('*.cc'))
objs += env.Object('SpeciallyTreatedFile.cc', CXXFLAGS='-O0')

Of course, that creates a problem for SCons:

scons: *** Two environments with different actions were specified
       for the same target: SpeciallyTreatedFile.o

I usually work around this using the following idiom:

objs = env.Object([f for f in Glob('*.cc')
  if 'SpeciallyTreatedFile.cc' not in f.path])

But that's pretty ugly, and gets even uglier if there's more than one file to be filtered out.

Is there a clearer way to do this?


Solution

  • I got fed up duplicating the [f for f in Glob ...] expression in several places, so I wrote the following helper method and added it to the build Environment:

    import os.path
    
    def filtered_glob(env, pattern, omit=[],
      ondisk=True, source=False, strings=False):
        return filter(
          lambda f: os.path.basename(f.path) not in omit,
          env.Glob(pattern))
    
    env.AddMethod(filtered_glob, "FilteredGlob");
    

    Now I can just write

    objs = env.Object(env.FilteredGlob('*.cc',
      ['SpeciallyTreatedFile.cc', 'SomeFileToIgnore.cc']))
    objs += env.Object('SpeciallyTreatedFile.cc', CXXFLAGS='-O0')
    

    Using this pattern it would be easy to write something similar that uses, say, a regexp filter as the omit argument instead of a simple list of filenames, but this works well for my current needs.