<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def build_specfile(target, source, env):
 """ Builds a RPM specfile from a dictionary with string metadata and by analyzing a tree of nodes. """

    file = open(target[0].get_abspath(), 'w')

    try:
        file.write( build_specfile_header(env) )
        file.write( build_specfile_sections(env) )
        file.write( build_specfile_filesection(env, source) )
        file.close()

        # call a user specified function
        if 'CHANGE_SPECFILE' in env:
            env['CHANGE_SPECFILE'](target, source)

    except KeyError as e:
        raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] )