1# Copyright 2022 Google LLC. 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"""Some utils""" 16 17load("//:visibility.bzl", "RULES_KOTLIN") 18 19# Mark targets that's aren't expected to build, but are needed for analysis test assertions. 20ONLY_FOR_ANALYSIS_TEST_TAGS = ["manual", "nobuilder", "only_for_analysis_test"] 21 22def create_file(name, content): 23 if content.startswith("\n"): 24 content = content[1:-1] 25 26 native.genrule( 27 name = "gen_" + name, 28 outs = [name], 29 cmd = """ 30cat > $@ <<EOF 31%s 32EOF 33""" % content, 34 ) 35 36 return name 37 38def _create_dir_impl(ctx): 39 dir = ctx.actions.declare_directory(ctx.attr.name) 40 41 command = "mkdir -p {0} " + ("&& cp {1} {0}" if ctx.files.srcs else "# {1}") 42 ctx.actions.run_shell( 43 command = command.format( 44 dir.path + "/" + ctx.attr.subdir, 45 " ".join([s.path for s in ctx.files.srcs]), 46 ), 47 inputs = ctx.files.srcs, 48 outputs = [dir], 49 ) 50 51 return [DefaultInfo(files = depset([dir]))] 52 53_create_dir = rule( 54 implementation = _create_dir_impl, 55 attrs = dict( 56 subdir = attr.string(), 57 srcs = attr.label_list(allow_files = True), 58 ), 59) 60 61def create_dir( 62 name, 63 subdir = None, 64 srcs = None): 65 _create_dir( 66 name = name, 67 subdir = subdir, 68 srcs = srcs, 69 ) 70 return name 71 72def get_action(actions, mnemonic): 73 """Get a specific action 74 75 Args: 76 actions: [List[Action]] 77 mnemonic: [string] Identify the action whose args to search 78 79 Returns: 80 [Optional[action]] The arg value, or None if it couldn't be found 81 """ 82 menmonic_actions = [a for a in actions if a.mnemonic == mnemonic] 83 if len(menmonic_actions) == 0: 84 return None 85 elif len(menmonic_actions) > 1: 86 fail("Expected a single '%s' action" % mnemonic) 87 88 return menmonic_actions[0] 89 90def get_arg(action, arg_name): 91 """Get a named arg from a specific action 92 93 Args: 94 action: [Optional[Action]] 95 arg_name: [string] 96 97 Returns: 98 [Optional[string]] The arg value, or None if it couldn't be found 99 """ 100 if not action: 101 return None 102 103 arg_values = [a for a in action.argv if a.startswith(arg_name)] 104 if len(arg_values) == 0: 105 return None 106 elif len(arg_values) > 1: 107 fail("Expected a single '%s' arg" % arg_name) 108 109 return arg_values[0][len(arg_name):] 110