|
@@ -77,3 +77,56 @@ static Error_manager loadProtobufFile(const std::string &file, ::google::protobu
|
|
return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s failed.", file.c_str()};
|
|
return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s failed.", file.c_str()};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
+
|
|
|
|
+static bool writeTxtProtobufFile(const std::string &file, const google::protobuf::Message &message) {
|
|
|
|
+ int fd = open(file.c_str(), std::ios::out);
|
|
|
|
+
|
|
|
|
+ FileOutputStream * output = new FileOutputStream(fd);
|
|
|
|
+
|
|
|
|
+ google::protobuf::TextFormat::Print(message, output);
|
|
|
|
+ delete output;
|
|
|
|
+ close(fd);
|
|
|
|
+ return true;
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+static bool writeJsonProtobufFile(const std::string &file, const google::protobuf::Message &message) {
|
|
|
|
+ std::string str;
|
|
|
|
+ google::protobuf::util::JsonPrintOptions options;
|
|
|
|
+ options.add_whitespace = true;
|
|
|
|
+ options.always_print_primitive_fields = true;
|
|
|
|
+ options.preserve_proto_field_names = true;
|
|
|
|
+ if (google::protobuf::util::MessageToJsonString(message, &str, options) != absl::OkStatus()) {
|
|
|
|
+ return false;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ //输出到文件
|
|
|
|
+ std::ofstream os;
|
|
|
|
+ os.open(file, std::ios::out);
|
|
|
|
+ if (!os.is_open())
|
|
|
|
+ std::cout << "error:can not find or create the file which named \" demo.json\"." << std::endl;
|
|
|
|
+ os << str;
|
|
|
|
+ os.close();
|
|
|
|
+ return true;
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+static Error_manager writeProtobufFile(const std::string &file, ::google::protobuf::Message &message) {
|
|
|
|
+ std::string ext = getFileExtension(file);
|
|
|
|
+ if (ext.empty()) {
|
|
|
|
+ return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s ext failed.", file.c_str()};
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ bool ret = false;
|
|
|
|
+ if (ext == "prototxt") {
|
|
|
|
+ ret = writeTxtProtobufFile(file, message);
|
|
|
|
+ } else if (ext == "json") {
|
|
|
|
+ ret = writeJsonProtobufFile(file, message);
|
|
|
|
+ } else {
|
|
|
|
+ return {PARSE_FAILED, MINOR_ERROR, "protobuf file %s type error.", file.c_str()};
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ if (ret) {
|
|
|
|
+ return {SUCCESS, NORMAL, "prase protobuf file %s success.", file.c_str()};
|
|
|
|
+ } else {
|
|
|
|
+ return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s failed.", file.c_str()};
|
|
|
|
+ }
|
|
|
|
+}
|