import os
from distutils.command import build_py
from distutils.dep_util import newer

class BuildPy(build_py.build_py):

    command_name = 'build_py'
    
    def finalize_options(self):
        build_py.build_py.finalize_options(self)

        self.config_filename = None
        if self.distribution.config_module:
            parts = self.distribution.config_module.split('.')
            self.config_filename = os.path.join(self.build_lib, *parts) + '.py'
        return

    def run(self):
        build_py.build_py.run(self)

        config = self.get_finalized_command('config')
        if (not self.dry_run and
            (self.config_filename and
             (self.force or
              newer(config.cache_filename, self.config_filename)))):
            # Create the configuration filename
            config.write_config_vars(self.config_filename)
        return

    def get_outputs(self, include_bytecode=1):
        outputs = build_py.build_py.get_outputs(self, include_bytecode)
        if self.config_filename:
            outputs.append(self.config_filename)
        return outputs
