blob: 1a3998478615de2e37b3ea547121d318f4eeb558 [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";
Alex Vakulenko07216fe2014-09-19 15:31:09 -070018const char kInvalidCategoryError[] = "invalid_category";
19const char kInvalidPackageError[] = "invalid_package";
Alex Vakulenkob04936f2014-09-19 14:53:58 -070020
21std::unique_ptr<const base::DictionaryValue> LoadJsonDict(
22 const base::FilePath& json_file_path, chromeos::ErrorPtr* error) {
23 std::unique_ptr<const base::DictionaryValue> result;
24 std::string json_string;
25 if (!base::ReadFileToString(json_file_path, &json_string)) {
26 chromeos::errors::system::AddSystemError(error, errno);
27 chromeos::Error::AddToPrintf(error, kErrorDomainBuffet,
28 kFileReadError,
29 "Failed to read file '%s'",
30 json_file_path.value().c_str());
31 return result;
32 }
33 std::string error_message;
34 base::Value* value = base::JSONReader::ReadAndReturnError(
35 json_string, base::JSON_PARSE_RFC, nullptr, &error_message);
36 if (!value) {
37 chromeos::Error::AddToPrintf(error, chromeos::errors::json::kDomain,
38 chromeos::errors::json::kParseError,
39 "Error parsing content of JSON file '%s': %s",
40 json_file_path.value().c_str(),
41 error_message.c_str());
42 return result;
43 }
44 const base::DictionaryValue* dict_value = nullptr;
45 if (!value->GetAsDictionary(&dict_value)) {
46 delete value;
47 chromeos::Error::AddToPrintf(error, chromeos::errors::json::kDomain,
48 chromeos::errors::json::kObjectExpected,
49 "Content of file '%s' is not a JSON object",
50 json_file_path.value().c_str());
51 return result;
52 }
53 result.reset(dict_value);
54 return result;
55}
56
57} // namespace buffet