OR-Tools  9.6
file_util.cc
Go to the documentation of this file.
1 // Copyright 2010-2022 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #include "ortools/util/file_util.h"
15 
16 #include <string>
17 
18 #include "absl/status/statusor.h"
19 #include "absl/strings/str_cat.h"
20 #include "google/protobuf/descriptor.h"
21 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
22 #include "google/protobuf/message.h"
23 #include "google/protobuf/text_format.h"
24 #include "google/protobuf/util/json_util.h"
25 #include "ortools/base/file.h"
27 #include "ortools/base/helpers.h"
28 #include "ortools/base/logging.h"
30 
31 namespace operations_research {
32 
33 using google::protobuf::util::JsonParseOptions;
34 using google::protobuf::util::JsonStringToMessage;
35 
36 absl::StatusOr<std::string> ReadFileToString(absl::string_view filename) {
37  std::string contents;
38  RETURN_IF_ERROR(file::GetContents(filename, &contents, file::Defaults()));
39  // Try decompressing it.
40  {
41  std::string uncompressed;
42  if (GunzipString(contents, &uncompressed)) contents.swap(uncompressed);
43  }
44  return contents;
45 }
46 
47 bool ReadFileToProto(absl::string_view filename,
48  google::protobuf::Message* proto) {
49  std::string data;
50  CHECK_OK(file::GetContents(filename, &data, file::Defaults()));
51  // Try decompressing it.
52  {
53  std::string uncompressed;
54  if (GunzipString(data, &uncompressed)) {
55  VLOG(1) << "ReadFileToProto(): input is gzipped";
56  data.swap(uncompressed);
57  }
58  }
59  // Try binary format first, then text format, then JSON, then proto3 JSON,
60  // then give up.
61  // For some of those, like binary format and proto3 JSON, we perform
62  // additional checks to verify that we have the right proto: it can happen
63  // to try to read a proto of type Foo as a proto of type Bar, by mistake, and
64  // we'd rather have this function fail rather than silently accept it, because
65  // the proto parser is too lenient with unknown fields.
66  // We don't require ByteSizeLong(parsed) == input.size(), because it may be
67  // the case that the proto version changed and some fields are dropped.
68  // We just fail when the difference is too large.
69  constexpr double kMaxBinaryProtoParseShrinkFactor = 2;
70  if (proto->ParseFromString(data)) {
71  // NOTE(user): When using ParseFromString() from a generic
72  // google::protobuf::Message, like we do here, all fields are stored, even
73  // if they are unknown in the underlying proto type. Unless we explicitly
74  // discard those 'unknown fields' here, our call to ByteSizeLong() will
75  // still count the unknown payload.
76  proto->DiscardUnknownFields();
77  if (proto->ByteSizeLong() <
78  data.size() / kMaxBinaryProtoParseShrinkFactor) {
79  VLOG(1) << "ReadFileToProto(): input may be a binary proto, but of a "
80  "different proto";
81  } else {
82  VLOG(1) << "ReadFileToProto(): input seems to be a binary proto";
83  return true;
84  }
85  }
86  if (google::protobuf::TextFormat::ParseFromString(data, proto)) {
87  VLOG(1) << "ReadFileToProto(): input is a text proto";
88  return true;
89  }
90  // We use `auto` here since protobuf does not use absl::Status.
91  const auto status = JsonStringToMessage(data, proto, JsonParseOptions());
92  if (!status.ok()) {
93  VLOG(1) << status;
94  } else {
95  // NOTE(user): We protect against the JSON proto3 parser being very lenient
96  // and easily accepting any JSON as a valid JSON for our proto: if the
97  // parsed proto's size is too small compared to the JSON, we probably parsed
98  // a JSON that wasn't representing a valid proto.
99  constexpr int kMaxJsonToBinaryShrinkFactor = 30;
100  if (proto->ByteSizeLong() < data.size() / kMaxJsonToBinaryShrinkFactor) {
101  VLOG(1) << "ReadFileToProto(): input is probably JSON, but probably not"
102  " of the right proto";
103  } else {
104  VLOG(1) << "ReadFileToProto(): input is a proto JSON";
105  return true;
106  }
107  }
108  LOG(WARNING) << "Could not parse protocol buffer";
109  return false;
110 }
111 
112 bool WriteProtoToFile(absl::string_view filename,
113  const google::protobuf::Message& proto,
114  ProtoWriteFormat proto_write_format, bool gzipped,
115  bool append_extension_to_file_name) {
116  std::string file_type_suffix;
117  std::string output_string;
118  google::protobuf::io::StringOutputStream stream(&output_string);
119  switch (proto_write_format) {
121  if (!proto.SerializeToZeroCopyStream(&stream)) {
122  LOG(WARNING) << "Serialize to stream failed.";
123  return false;
124  }
125  file_type_suffix = ".bin";
126  break;
128  if (!google::protobuf::TextFormat::PrintToString(proto, &output_string)) {
129  LOG(WARNING) << "Printing to string failed.";
130  return false;
131  }
132  break;
134  google::protobuf::util::JsonPrintOptions options;
135  options.add_whitespace = true;
136  options.always_print_primitive_fields = true;
137  options.preserve_proto_field_names = true;
138  if (!google::protobuf::util::MessageToJsonString(proto, &output_string,
139  options)
140  .ok()) {
141  LOG(WARNING) << "Printing to stream failed.";
142  return false;
143  }
144  file_type_suffix = ".json";
145  break;
146  }
148  google::protobuf::util::JsonPrintOptions options;
149  options.add_whitespace = true;
150  if (!google::protobuf::util::MessageToJsonString(proto, &output_string,
151  options)
152  .ok()) {
153  LOG(WARNING) << "Printing to stream failed.";
154  return false;
155  }
156  file_type_suffix = ".json";
157  break;
158  }
159  if (gzipped) {
160  std::string gzip_string;
161  GzipString(output_string, &gzip_string);
162  output_string.swap(gzip_string);
163  file_type_suffix += ".gz";
164  }
165  std::string output_filename(filename);
166  if (append_extension_to_file_name) output_filename += file_type_suffix;
167  VLOG(1) << "Writing " << output_string.size() << " bytes to "
168  << output_filename;
169  if (!file::SetContents(output_filename, output_string, file::Defaults())
170  .ok()) {
171  LOG(WARNING) << "Writing to file failed.";
172  return false;
173  }
174  return true;
175 }
176 
177 } // namespace operations_research
#define RETURN_IF_ERROR(expr)
CpModelProto proto
absl::Status status
Definition: g_gurobi.cc:41
void GzipString(absl::string_view uncompressed, std::string *compressed)
Definition: gzipstring.h:63
bool GunzipString(const std::string &str, std::string *out)
Definition: gzipstring.h:22
absl::Status GetContents(const absl::string_view &filename, std::string *output, int flags)
Definition: base/file.cc:164
Options Defaults()
Definition: base/file.h:123
absl::Status SetContents(const absl::string_view &filename, const absl::string_view &contents, int flags)
Definition: base/file.cc:205
Collection of objects used to extend the Constraint Solver library.
absl::StatusOr< std::string > ReadFileToString(absl::string_view filename)
Definition: file_util.cc:36
bool WriteProtoToFile(absl::string_view filename, const google::protobuf::Message &proto, ProtoWriteFormat proto_write_format, bool gzipped, bool append_extension_to_file_name)
Definition: file_util.cc:112
bool ReadFileToProto(absl::string_view filename, google::protobuf::Message *proto)
Definition: file_util.cc:47
#define VLOG(verboselevel)
Definition: vlog.h:39