blob: 2ea454b1e8232338166338dbe4ea65047c3e162d [file] [log] [blame]
#ifndef PRODUCTION_SUSHID_SAFEPOWER_AGENT_PARSE_TEXT_PROTO_H_
#define PRODUCTION_SUSHID_SAFEPOWER_AGENT_PARSE_TEXT_PROTO_H_
#include <string>
#include <utility>
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/io/tokenizer.h"
#include "google/protobuf/text_format.h"
namespace safepower_agent {
namespace internal {
class ErrorCollector : public google::protobuf::io::ErrorCollector {
public:
explicit ErrorCollector(absl::string_view text_proto)
: text_proto_(text_proto) {}
ErrorCollector(const ErrorCollector&) = delete;
ErrorCollector& operator=(const ErrorCollector&) = delete;
void RecordError(int line, google::protobuf::io::ColumnNumber column,
absl::string_view message) override;
void RecordWarning(int line, google::protobuf::io::ColumnNumber column,
absl::string_view message) override;
std::string message() && { return std::move(message_); }
private:
absl::string_view text_proto_;
std::string message_;
};
} // namespace internal
template <typename Proto>
absl::StatusOr<Proto> ParseTextProto(absl::string_view text_proto) {
google::protobuf::TextFormat::Parser parser;
internal::ErrorCollector error_collector(text_proto);
parser.RecordErrorsTo(&error_collector);
Proto proto;
if (!parser.ParseFromString(text_proto, &proto)) {
return absl::InvalidArgumentError(std::move(error_collector).message());
}
return proto;
}
} // namespace safepower_agent
#endif // PRODUCTION_SUSHID_SAFEPOWER_AGENT_PARSE_TEXT_PROTO_H_