defs.bzl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. if ctx.attr.strip_package_dir:
  10. # Files may or may not be prefixed with the bin directory, and then
  11. # may or may not be prefixed with the package directory. Strip both.
  12. bin_dir = ctx.bin_dir.path + "/"
  13. package_dir = ctx.label.package + "/"
  14. files_stripped = [f.removeprefix(bin_dir).removeprefix(package_dir) for f in files]
  15. else:
  16. files_stripped = files
  17. return files_stripped
  18. def _manifest(ctx):
  19. out = ctx.actions.declare_file(ctx.label.name)
  20. files = _get_files(ctx)
  21. ctx.actions.write(out, "\n".join(files) + "\n")
  22. return [
  23. DefaultInfo(
  24. files = depset(direct = [out]),
  25. runfiles = ctx.runfiles(files = [out]),
  26. ),
  27. ]
  28. # Produces the manifest as a series of lines.
  29. manifest = rule(
  30. implementation = _manifest,
  31. attrs = {
  32. "srcs": attr.label_list(allow_files = True, mandatory = True),
  33. "strip_package_dir": attr.bool(default = False),
  34. },
  35. )
  36. def _manifest_as_cpp(ctx):
  37. out = ctx.actions.declare_file(ctx.label.name)
  38. files = _get_files(ctx)
  39. lines = [
  40. "// Auto-generated by manifest_as_cpp.",
  41. "const char* {0}[] = {{".format(ctx.attr.var_name),
  42. ]
  43. lines += [
  44. " \"{0}\",".format(file)
  45. for file in files
  46. ]
  47. lines += [
  48. " nullptr,",
  49. "};",
  50. ]
  51. ctx.actions.write(out, "\n".join(lines) + "\n")
  52. return [
  53. DefaultInfo(
  54. files = depset(direct = [out]),
  55. runfiles = ctx.runfiles(files = [out]),
  56. ),
  57. ]
  58. # Produces the manifest as a nullptr-terminated `const char* var_name[]`.
  59. # Use with `extern const char* var_name[];`.
  60. manifest_as_cpp = rule(
  61. implementation = _manifest_as_cpp,
  62. attrs = {
  63. "srcs": attr.label_list(allow_files = True, mandatory = True),
  64. "strip_package_dir": attr.bool(default = False),
  65. "var_name": attr.string(mandatory = True),
  66. },
  67. )