example.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import sys
  2. from google.protobuf import text_format
  3. from foo import bar_pb2
  4. from com_envoyproxy_protoc_gen_validate.python.protoc_gen_validate import validator
  5. from typing import List
  6. def main(filenames: List[str]) -> None:
  7. if not filenames:
  8. print("No inputs provided; exiting")
  9. success_count = 0
  10. for filename in filenames:
  11. bars = bar_pb2.Bars()
  12. fullname = bars.DESCRIPTOR.name
  13. try:
  14. with open(filename, 'r') as fh:
  15. text_format.Parse(fh.read(), bars)
  16. except IOError as error:
  17. msg = f"Failed to open file '{filename}': {error}"
  18. raise RuntimeError(msg) from error
  19. except text_format.ParseError as error:
  20. msg = f"Failed to parse file '{filename}' as a {fullname} textproto: {error}"
  21. raise RuntimeError(msg) from error
  22. try:
  23. validator.validate(bars)
  24. except validator.ValidationFailed as error:
  25. print(
  26. f"Failed to validate file '{filename}' as a {fullname} textproto: {error}",
  27. file=sys.stderr,
  28. )
  29. else:
  30. print(f"Successfully validated file '{filename}' as a {fullname} textproto")
  31. success_count += 1
  32. failure_count = len(filenames) - success_count
  33. if failure_count:
  34. s = "s" if failure_count > 1 else ""
  35. msg = f"Failed to validate {failure_count} file{s}"
  36. raise RuntimeError(msg)
  37. if __name__ == "__main__":
  38. try:
  39. main(sys.argv[1:])
  40. except RuntimeError as error:
  41. print(error, file=sys.stderr)
  42. sys.exit(1)