gen_rust_module.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. import argparse
  10. import os
  11. import sys
  12. """
  13. We invoke this script (via Bazel) and provide paths to the volatile and stable
  14. variable files that this scripts parses and then generates a Rust file with
  15. all the variables as static values.
  16. See <https://bazel.build/docs/user-manual#workspace-status> for more info on
  17. what these files are.
  18. """
  19. def main():
  20. parser = argparse.ArgumentParser(
  21. description="Generate a Rust module with build-info"
  22. )
  23. parser.add_argument(
  24. "--rust_file",
  25. required=True,
  26. help="path of the Rust file this script will generate",
  27. )
  28. parser.add_argument(
  29. "--volatile_file",
  30. required=True,
  31. help="file generated by Bazel that includes the 'volatile' variables",
  32. )
  33. parser.add_argument(
  34. "--stable_file",
  35. required=True,
  36. help="file generated by Bazel that includes the 'stable' variables",
  37. )
  38. args = parser.parse_args()
  39. volatile_variables = parse_variable_file(args.volatile_file)
  40. stable_variables = parse_variable_file(args.stable_file)
  41. # Make sure the parent directory of the destination exists.
  42. output_dir = os.path.dirname(args.rust_file)
  43. if not os.path.exists(output_dir):
  44. os.makedirs(output_dir)
  45. with open(args.rust_file, "w") as f:
  46. for k, v in volatile_variables.items():
  47. key_name = k.upper()
  48. f.write(f'pub const {key_name}: &str = "{v}";\n')
  49. for k, v in stable_variables.items():
  50. key_name = k.upper()
  51. f.write(f'pub const {key_name}: &str = "{v}";\n')
  52. def parse_variable_file(path) -> dict[str, str]:
  53. variables = {}
  54. with open(path) as f:
  55. for line in f.read().splitlines(keepends=False):
  56. if not line:
  57. continue
  58. # Note: The key value format of this Bazel generated file is that
  59. # the first space is what splits keys from their value.
  60. key_value = line.split(" ", 1)
  61. key = key_value[0].strip()
  62. if key in variables:
  63. sys.stderr.write(f"Error: Found duplicate key '{key}'\n")
  64. sys.exit(1)
  65. if len(key_value) == 1:
  66. sys.stderr.write(f"Error: No value for key '{key}'\n")
  67. sys.exit(1)
  68. variables[key] = key_value[1].strip()
  69. return variables
  70. if __name__ == "__main__":
  71. main()