defs.bzl 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. # Exceptions. See /LICENSE for license information.
  3. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. """Rule for producing a manifest for a filegroup."""
  5. def _get_files(ctx):
  6. files = []
  7. for src in ctx.attr.srcs:
  8. files.extend([f.path for f in src[DefaultInfo].files.to_list()])
  9. files.extend([
  10. f.path
  11. for f in src[DefaultInfo].default_runfiles.files.to_list()
  12. ])
  13. if ctx.attr.strip_package_dir:
  14. package_dir = ctx.label.package + "/"
  15. files_stripped = [f.removeprefix(package_dir) for f in files]
  16. else:
  17. files_stripped = files
  18. return files_stripped
  19. def _manifest(ctx):
  20. out = ctx.actions.declare_file(ctx.label.name)
  21. files = _get_files(ctx)
  22. ctx.actions.write(out, "\n".join(files) + "\n")
  23. return [
  24. DefaultInfo(
  25. files = depset(direct = [out]),
  26. runfiles = ctx.runfiles(files = [out]),
  27. ),
  28. ]
  29. # Produces the manifest as a series of lines.
  30. manifest = rule(
  31. implementation = _manifest,
  32. attrs = {
  33. "srcs": attr.label_list(allow_files = True, mandatory = True),
  34. "strip_package_dir": attr.bool(default = False),
  35. },
  36. )
  37. def _manifest_as_cpp(ctx):
  38. out = ctx.actions.declare_file(ctx.label.name)
  39. files = _get_files(ctx)
  40. lines = [
  41. "// Auto-generated by manifest_as_cpp.",
  42. "const char* {0}[] = {{".format(ctx.attr.var_name),
  43. ]
  44. lines += [
  45. " \"{0}\",".format(file)
  46. for file in files
  47. ]
  48. lines += [
  49. " nullptr,",
  50. "};",
  51. ]
  52. ctx.actions.write(out, "\n".join(lines) + "\n")
  53. return [
  54. DefaultInfo(
  55. files = depset(direct = [out]),
  56. runfiles = ctx.runfiles(files = [out]),
  57. ),
  58. ]
  59. # Produces the manifest as a nullptr-terminated `const char* var_name[]`.
  60. # Use with `extern const char* var_name[];`.
  61. manifest_as_cpp = rule(
  62. implementation = _manifest_as_cpp,
  63. attrs = {
  64. "srcs": attr.label_list(allow_files = True, mandatory = True),
  65. "strip_package_dir": attr.bool(default = False),
  66. "var_name": attr.string(mandatory = True),
  67. },
  68. )