def add_command_hooks(commands, srcdir='.'):
    """
    Look through setup_package.py modules for functions with names like
    ``pre_<command_name>_hook`` and ``post_<command_name>_hook`` where
    ``<command_name>`` is the name of a ``setup.py`` command (e.g. build_ext).

    If either hook is present this adds a wrapped version of that command to
    the passed in ``commands`` `dict`.  ``commands`` may be pre-populated with
    other custom distutils command classes that should be wrapped if there are
    hooks for them (e.g. `AstropyBuildPy`).
    """

    hook_re = re.compile(r'^(pre|post)_(.+)_hook$')

    # Distutils commands have a method of the same name, but it is not a
    # *classmethod* (which probably didn't exist when distutils was first
    # written)
    def get_command_name(cmdcls):
        if hasattr(cmdcls, 'command_name'):
            return cmdcls.command_name
        else:
            return cmdcls.__name__

    packages = find_packages(srcdir)
    dist = get_dummy_distribution()

    hooks = collections.defaultdict(dict)

    for setuppkg in iter_setup_packages(srcdir, packages):
        for name, obj in vars(setuppkg).items():
            match = hook_re.match(name)
            if not match:
                continue

            hook_type = match.group(1)
            cmd_name = match.group(2)

            if hook_type not in hooks[cmd_name]:
                hooks[cmd_name][hook_type] = []

            hooks[cmd_name][hook_type].append((setuppkg.__name__, obj))

    for cmd_name, cmd_hooks in hooks.items():
        commands[cmd_name] = generate_hooked_command(
            cmd_name, dist.get_command_class(cmd_name), cmd_hooks)