1# Copyright 2023 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Text manipulation utilities useful for repository rule writing.""" 16 17def _indent(text, indent = " " * 4): 18 if "\n" not in text: 19 return indent + text 20 21 return "\n".join([indent + line for line in text.splitlines()]) 22 23def _render_alias(name, actual): 24 return "\n".join([ 25 "alias(", 26 _indent("name = \"{}\",".format(name)), 27 _indent("actual = {},".format(actual)), 28 ")", 29 ]) 30 31def _render_dict(d): 32 return "\n".join([ 33 "{", 34 _indent("\n".join([ 35 "{}: {},".format(repr(k), repr(v)) 36 for k, v in d.items() 37 ])), 38 "}", 39 ]) 40 41def _render_select(selects, *, no_match_error = None): 42 dict_str = _render_dict(selects) + "," 43 44 if no_match_error: 45 args = "\n".join([ 46 "", 47 _indent(dict_str), 48 _indent("no_match_error = {},".format(no_match_error)), 49 "", 50 ]) 51 else: 52 args = "\n".join([ 53 "", 54 _indent(dict_str), 55 "", 56 ]) 57 58 return "select({})".format(args) 59 60render = struct( 61 indent = _indent, 62 alias = _render_alias, 63 dict = _render_dict, 64 select = _render_select, 65) 66