gen_provenance_metadata.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (C) 2022 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import argparse
  17. import hashlib
  18. import sys
  19. import google.protobuf.text_format as text_format
  20. import provenance_metadata_pb2
  21. def Log(*info):
  22. if args.verbose:
  23. for i in info:
  24. print(i)
  25. def ParseArgs(argv):
  26. parser = argparse.ArgumentParser(description='Create provenance metadata for a prebuilt artifact')
  27. parser.add_argument('-v', '--verbose', action='store_true', help='Print more information in execution')
  28. parser.add_argument('--module_name', help='Module name', required=True)
  29. parser.add_argument('--artifact_path', help='Relative path of the prebuilt artifact in source tree', required=True)
  30. parser.add_argument('--install_path', help='Absolute path of the artifact in the filesystem images', required=True)
  31. parser.add_argument('--metadata_path', help='Path of the provenance metadata file created for the artifact', required=True)
  32. return parser.parse_args(argv)
  33. def main(argv):
  34. global args
  35. args = ParseArgs(argv)
  36. Log("Args:", vars(args))
  37. provenance_metadata = provenance_metadata_pb2.ProvenanceMetadata()
  38. provenance_metadata.module_name = args.module_name
  39. provenance_metadata.artifact_path = args.artifact_path
  40. provenance_metadata.artifact_install_path = args.install_path
  41. Log("Generating SHA256 hash")
  42. h = hashlib.sha256()
  43. with open(args.artifact_path, "rb") as artifact_file:
  44. h.update(artifact_file.read())
  45. provenance_metadata.artifact_sha256 = h.hexdigest()
  46. text_proto = [
  47. "# proto-file: build/soong/provenance/proto/provenance_metadata.proto",
  48. "# proto-message: ProvenanceMetaData",
  49. "",
  50. text_format.MessageToString(provenance_metadata)
  51. ]
  52. with open(args.metadata_path, "wt") as metadata_file:
  53. file_content = "\n".join(text_proto)
  54. Log("Writing provenance metadata in textproto:", file_content)
  55. metadata_file.write(file_content)
  56. if __name__ == '__main__':
  57. main(sys.argv[1:])