1 //
2 // Copyright (C) 2022 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include <memory>
17 #include <string>
18 #include <string_view>
19 
20 #include "common/libs/fs/shared_buf.h"
21 #include "common/libs/fs/shared_fd.h"
22 #include "common/libs/utils/json.h"
23 
24 namespace cuttlefish {
25 
ParseJson(std::string_view input)26 Result<Json::Value> ParseJson(std::string_view input) {
27   Json::Value root;
28   JSONCPP_STRING err;
29   Json::CharReaderBuilder builder;
30   const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
31   auto begin = input.data();
32   auto end = begin + input.length();
33   CF_EXPECT(reader->parse(begin, end, &root, &err), err);
34   return root;
35 }
36 
LoadFromFile(SharedFD json_fd)37 Result<Json::Value> LoadFromFile(SharedFD json_fd) {
38   CF_EXPECT(json_fd->IsOpen(), "json_fd is not open.");
39   std::string json_contents;
40   // on success, this must return a positive integer
41   CF_EXPECT_GE(ReadAll(json_fd, &json_contents), 0,
42                "ReadAll() failed and returned 0 or -1");
43   Json::Value json_value = CF_EXPECTF(
44       ParseJson(json_contents), "Failed to parse json: \n{}", json_contents);
45   return json_value;
46 }
47 
LoadFromFile(const std::string & path_to_file)48 Result<Json::Value> LoadFromFile(const std::string& path_to_file) {
49   SharedFD json_fd = SharedFD::Open(path_to_file, O_RDONLY);
50   auto json_value =
51       CF_EXPECTF(LoadFromFile(json_fd), "Failed to open {}", path_to_file);
52   return json_value;
53 }
54 
55 }  // namespace cuttlefish
56