github.com/bazelbuild/rules_webtesting@v0.2.0/web/internal/collections.bzl (about) 1 # Copyright 2016 Google Inc. 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 """Collections module contains util functions for working with collections. 15 16 Usage: 17 load("//web/build_defs:collections.bzl", "lists", "maps") 18 19 l = lists.clone(l) 20 lists.ensure_contains(l, "//some:target") 21 """ 22 23 def _is_list_like(val): 24 """Checks is val is a list-like (list, depset, tuple) value.""" 25 return (type(val) in [type([]), type(depset()), type(())]) 26 27 def _list_ensure_contains(lst, item): 28 """Appends the specified item to the list if its not already a member.""" 29 if item not in lst: 30 lst.append(item) 31 32 def _list_ensure_contains_all(lst, items): 33 """Appends the specified items to the list if not already members.""" 34 for item in items: 35 _list_ensure_contains(lst, item) 36 37 def _list_clone(original): 38 """Create a new list with content of original.""" 39 if _is_list_like(original): 40 return list(original) 41 if original: 42 fail("got \"" + original + "\", but expected none or a list-like value") 43 return [] 44 45 lists = struct( 46 clone = _list_clone, 47 ensure_contains = _list_ensure_contains, 48 ensure_contains_all = _list_ensure_contains_all, 49 is_list_like = _is_list_like, 50 ) 51 52 def _map_clone(original): 53 new_map = {} 54 if original: 55 new_map.update(original) 56 return new_map 57 58 maps = struct(clone = _map_clone)