def apply_flags_to_spec(spec, flags):
    """
    Returns a copy of the component list but with the given flags applied; any component or
    attribute that doesn't match the given flags are omitted.
    """
    # If we are not using flags, then no filtering is required.
    if "flag_defaults" not in spec:
        return spec

    components = []
    for comp in spec["components"]:
        if all(comp['flags'][key] == value for key, value in flags.items()):
            new_comp = {"attributes": []}
            for key, value in comp.items():
                if key in {"flags", "attributes"}:
                    continue
                new_comp[key] = value
            for attr in comp["attributes"]:
                if all(attr['flags'][key] == value for key, value in flags.items()):
                    new_attr = {}
                    for key, value in attr.items():
                        if key in {"flags"}:
                            continue
                        new_attr[key] = value
                    new_comp["attributes"].append(new_attr)
            components.append(new_comp)
    return components