xref: /aosp_15_r20/external/bazel-skylib/lib/structs.bzl (revision bcb5dc7965af6ee42bf2f21341a2ec00233a8c8a)
1*bcb5dc79SHONG Yifan# Copyright 2017 The Bazel Authors. All rights reserved.
2*bcb5dc79SHONG Yifan#
3*bcb5dc79SHONG Yifan# Licensed under the Apache License, Version 2.0 (the "License");
4*bcb5dc79SHONG Yifan# you may not use this file except in compliance with the License.
5*bcb5dc79SHONG Yifan# You may obtain a copy of the License at
6*bcb5dc79SHONG Yifan#
7*bcb5dc79SHONG Yifan#    http://www.apache.org/licenses/LICENSE-2.0
8*bcb5dc79SHONG Yifan#
9*bcb5dc79SHONG Yifan# Unless required by applicable law or agreed to in writing, software
10*bcb5dc79SHONG Yifan# distributed under the License is distributed on an "AS IS" BASIS,
11*bcb5dc79SHONG Yifan# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12*bcb5dc79SHONG Yifan# See the License for the specific language governing permissions and
13*bcb5dc79SHONG Yifan# limitations under the License.
14*bcb5dc79SHONG Yifan
15*bcb5dc79SHONG Yifan"""Skylib module containing functions that operate on structs."""
16*bcb5dc79SHONG Yifan
17*bcb5dc79SHONG Yifandef _to_dict(s):
18*bcb5dc79SHONG Yifan    """Converts a `struct` to a `dict`.
19*bcb5dc79SHONG Yifan
20*bcb5dc79SHONG Yifan    Args:
21*bcb5dc79SHONG Yifan      s: A `struct`.
22*bcb5dc79SHONG Yifan
23*bcb5dc79SHONG Yifan    Returns:
24*bcb5dc79SHONG Yifan      A `dict` whose keys and values are the same as the fields in `s`. The
25*bcb5dc79SHONG Yifan      transformation is only applied to the struct's fields and not to any
26*bcb5dc79SHONG Yifan      nested values.
27*bcb5dc79SHONG Yifan    """
28*bcb5dc79SHONG Yifan
29*bcb5dc79SHONG Yifan    # to_json()/to_proto() are disabled by --incompatible_struct_has_no_methods
30*bcb5dc79SHONG Yifan    # and will be removed entirely in a future Bazel release.
31*bcb5dc79SHONG Yifan    return {
32*bcb5dc79SHONG Yifan        key: getattr(s, key)
33*bcb5dc79SHONG Yifan        for key in dir(s)
34*bcb5dc79SHONG Yifan        if key != "to_json" and key != "to_proto"
35*bcb5dc79SHONG Yifan    }
36*bcb5dc79SHONG Yifan
37*bcb5dc79SHONG Yifanstructs = struct(
38*bcb5dc79SHONG Yifan    to_dict = _to_dict,
39*bcb5dc79SHONG Yifan)
40