def extract_build_cmds(commands, exe_name):
    """Extracts build command information from `ninja -t commands` output.

    Args:
        commands: String containing the output of `ninja -t commands` for the
            libcxx_test_template.
        exe_name: The basename of the built executable.

    Returns:
        Tuple of (compiler, compiler_flags, linker_flags).
    """
    cc = None
    cflags = None
    ldflags = None
    template_name = 'external/libcxx/libcxx_test_template.cpp'

    for cmd in commands.splitlines():
        cmd_args = cmd.split()
        if cc is None and template_name in cmd_args:
            for i, arg in enumerate(cmd_args):
                if arg == '-o':
                    cmd_args[i + 1] = '%OUT%'
                elif arg == template_name:
                    cmd_args[i] = '%SOURCE%'
                # Drop dependency tracking args since they can cause file
                # not found errors at test time.
                if arg == '-MD':
                    cmd_args[i] = ''
                if arg == '-MF':
                    cmd_args[i] = ''
                    cmd_args[i + 1] = ''
            if cmd_args[0] == 'PWD=/proc/self/cwd':
                cmd_args = cmd_args[1:]
            if cmd_args[0].endswith('gomacc'):
                cmd_args = cmd_args[1:]
            cc = cmd_args[0]
            cflags = cmd_args[1:]
        if ldflags is None:
            is_ld = False
            for i, arg in enumerate(cmd_args):
                # Here we assume that the rspfile contains the path to the
                # object file and nothing else.
                if arg.startswith('@'):
                    cmd_args[i] = '%SOURCE%'
                if arg == '-o' and cmd_args[i + 1].endswith(exe_name):
                    cmd_args[i + 1] = '%OUT%'
                    is_ld = True
            if is_ld:
                ldflags = cmd_args[1:]

    return cc, cflags, ldflags