blob: 71e9a56e822be983b6259ecc3652e9b954a40dcf [file] [log] [blame]
Alex Vakulenkob04936f2014-09-19 14:53:58 -07001// Copyright 2014 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "buffet/utils.h"
6
7#include <map>
8#include <string>
9
10#include <base/files/file_util.h>
11#include <base/json/json_reader.h>
12#include <chromeos/errors/error_codes.h>
13
14namespace buffet {
15
16const char kErrorDomainBuffet[] = "buffet";
17const char kFileReadError[] = "file_read_error";
18
19std::unique_ptr<const base::DictionaryValue> LoadJsonDict(
20 const base::FilePath& json_file_path, chromeos::ErrorPtr* error) {
21 std::unique_ptr<const base::DictionaryValue> result;
22 std::string json_string;
23 if (!base::ReadFileToString(json_file_path, &json_string)) {
24 chromeos::errors::system::AddSystemError(error, errno);
25 chromeos::Error::AddToPrintf(error, kErrorDomainBuffet,
26 kFileReadError,
27 "Failed to read file '%s'",
28 json_file_path.value().c_str());
29 return result;
30 }
31 std::string error_message;
32 base::Value* value = base::JSONReader::ReadAndReturnError(
33 json_string, base::JSON_PARSE_RFC, nullptr, &error_message);
34 if (!value) {
35 chromeos::Error::AddToPrintf(error, chromeos::errors::json::kDomain,
36 chromeos::errors::json::kParseError,
37 "Error parsing content of JSON file '%s': %s",
38 json_file_path.value().c_str(),
39 error_message.c_str());
40 return result;
41 }
42 const base::DictionaryValue* dict_value = nullptr;
43 if (!value->GetAsDictionary(&dict_value)) {
44 delete value;
45 chromeos::Error::AddToPrintf(error, chromeos::errors::json::kDomain,
46 chromeos::errors::json::kObjectExpected,
47 "Content of file '%s' is not a JSON object",
48 json_file_path.value().c_str());
49 return result;
50 }
51 result.reset(dict_value);
52 return result;
53}
54
55} // namespace buffet