| #ifndef PRODUCTION_SUSHID_SAFEPOWER_AGENT_BMC_PROTO_READER_H_ |
| #define PRODUCTION_SUSHID_SAFEPOWER_AGENT_BMC_PROTO_READER_H_ |
| |
| #include <filesystem> // NOLINT(build/c++17) |
| #include <string> |
| |
| #include "absl/log/log.h" |
| #include "absl/status/status.h" |
| #include "absl/status/statusor.h" |
| #include "absl/strings/string_view.h" |
| |
| namespace proto_reader { |
| |
| absl::StatusOr<std::string> ReadFileToString( |
| const std::filesystem::path& file_name); |
| |
| absl::Status WriteFileToString(const std::filesystem::path& file_name, |
| absl::string_view content); |
| template <typename T> |
| inline absl::StatusOr<T> ReadProto(const std::filesystem::path& proto_path) { |
| if (!std::filesystem::exists(proto_path) || |
| !std::filesystem::is_regular_file(proto_path)) { |
| LOG(ERROR) << "proto file " << proto_path << " not found"; |
| return absl::NotFoundError("proto file error"); |
| } |
| absl::StatusOr<std::string> serialized_proto = ReadFileToString(proto_path); |
| if (!serialized_proto.ok()) { |
| return serialized_proto.status(); |
| } |
| if (T proto; proto.ParseFromString(*serialized_proto)) { |
| return proto; |
| } else { |
| LOG(ERROR) << "Failed to deserialize the proto file" << proto_path; |
| return absl::InvalidArgumentError("Failed to deserialize the proto file"); |
| } |
| } |
| |
| template <typename T> |
| inline absl::Status WriteProto(const std::filesystem::path& proto_path, |
| T in_proto) { |
| std::string str_proto; |
| if (!in_proto.SerializeToString(&str_proto)) { |
| LOG(ERROR) << "Failed to serialize message."; |
| return absl::InvalidArgumentError("Failed to serialize the proto file"); |
| } |
| return WriteFileToString(proto_path, str_proto); |
| } |
| |
| } // namespace proto_reader |
| |
| #endif // PRODUCTION_SUSHID_SAFEPOWER_AGENT_BMC_PROTO_READER_H_ |