1# Copyright 2024 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"""Rules to filter files from a directory.""" 15 16load(":providers.bzl", "DirectoryInfo") 17 18def _directory_glob_impl(ctx): 19 directory = ctx.attr.directory[DirectoryInfo] 20 srcs = directory.glob( 21 ctx.attr.srcs, 22 exclude = ctx.attr.exclude, 23 allow_empty = ctx.attr.allow_empty, 24 ) 25 data = directory.glob( 26 ctx.attr.data, 27 exclude = ctx.attr.exclude, 28 allow_empty = ctx.attr.allow_empty, 29 ) 30 31 return DefaultInfo( 32 files = srcs, 33 runfiles = ctx.runfiles(transitive_files = depset(transitive = [srcs, data])), 34 ) 35 36directory_glob = rule( 37 implementation = _directory_glob_impl, 38 attrs = { 39 "allow_empty": attr.bool( 40 doc = "If true, allows globs to not match anything.", 41 ), 42 "data": attr.string_list( 43 doc = """A list of globs to files within the directory to put in the runfiles. 44 45For example, `data = ["foo/**"]` would collect all files contained within `<directory>/foo` into the 46runfiles.""", 47 ), 48 "directory": attr.label(providers = [DirectoryInfo], mandatory = True), 49 "exclude": attr.string_list( 50 doc = "A list of globs to files within the directory to exclude from the files and runfiles.", 51 ), 52 "srcs": attr.string_list( 53 doc = """A list of globs to files within the directory to put in the files. 54 55For example, `srcs = ["foo/**"]` would collect the file at `<directory>/foo` into the 56files.""", 57 ), 58 }, 59 doc = """globs files from a directory by relative path. 60 61Usage: 62 63``` 64directory_glob( 65 name = "foo", 66 directory = ":directory", 67 srcs = ["foo/bar"], 68 data = ["foo/**"], 69 exclude = ["foo/**/*.h"] 70) 71``` 72""", 73) 74