example.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <fcntl.h>
  2. #include <unistd.h>
  3. #include <cstdlib>
  4. #include <ostream>
  5. #include "google/protobuf/io/zero_copy_stream_impl.h"
  6. #include "google/protobuf/text_format.h"
  7. #include "foo/bar.pb.h"
  8. #include "foo/bar.pb.validate.h"
  9. int main(const int nargs, const char** const args) {
  10. if (nargs <= 1) {
  11. std::cout << "No inputs provided; exiting" << std::endl;
  12. return EXIT_SUCCESS;
  13. }
  14. int success_count = 0;
  15. for (int i = 1; i < nargs; ++i) {
  16. pgv::example::foo::Bars bars;
  17. const auto filename = args[i];
  18. const auto fd = ::open(filename, O_RDONLY);
  19. if (fd < 0) {
  20. std::cerr << "Failed to open file '" << filename << "'" << std::endl;
  21. continue;
  22. }
  23. google::protobuf::io::FileInputStream input(fd);
  24. input.SetCloseOnDelete(true);
  25. if (!google::protobuf::TextFormat::Parse(&input, &bars)) {
  26. std::cerr << "Failed to parse file '" << filename << "' as a "
  27. << bars.GetDescriptor()->full_name() << " textproto" << std::endl;
  28. return EXIT_FAILURE;
  29. }
  30. pgv::ValidationMsg error_message;
  31. if (Validate(bars, &error_message)) {
  32. std::cout << "Successfully validated file '" << filename << "' as a "
  33. << bars.GetDescriptor()->full_name() << " textproto"
  34. << std::endl;
  35. ++success_count;
  36. } else {
  37. std::cerr << "Failed to validate file '" << filename << "' as a "
  38. << bars.GetDescriptor()->full_name()
  39. << " textproto: " << error_message << std::endl;
  40. }
  41. }
  42. const int failure_count = nargs - 1 - success_count;
  43. if (failure_count != 0) {
  44. std::cerr << "Failed to validate " << failure_count << " file"
  45. << (failure_count == 1 ? "" : "s") << std::endl;
  46. return EXIT_FAILURE;
  47. }
  48. return EXIT_SUCCESS;
  49. }