import re


def set_filename_version(filename, version_number, pattern):
    """Write the given version number in the given (in filename) file,
    after the given pattern.

    E.g.:
        set_filename_version('setup.py', '1.0.0', 'version')

    Extracted from Flask source, see:
        - file: flask/scripts/make-release.py
        - commit: 54688b26a9562c9a9c31541dbf32e0d8ee7a5926

    """
    changed = []

    def inject_version(match):
        before, old, after = match.groups()
        changed.append(True)
        return before + version_number + after

    with open(filename) as f:
        contents = re.sub(r"""^(\s*%s\s*=\s*")(.+?)(")(?sm)""" % pattern, inject_version, f.read())

    if not changed:
        raise Exception("Could not find %s in %s", pattern, filename)

    with open(filename, "w") as f:
        f.write(contents)