blob: 9cd727179b5bca1e299abe6cc9a8fbd51c8d7335 [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)) {
Alex Vakulenkoac8037d2014-11-11 11:42:05 -080026 chromeos::errors::system::AddSystemError(error, FROM_HERE, errno);
27 chromeos::Error::AddToPrintf(error, FROM_HERE, kErrorDomainBuffet,
Alex Vakulenkob04936f2014-09-19 14:53:58 -070028 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) {
Alex Vakulenkoac8037d2014-11-11 11:42:05 -080037 chromeos::Error::AddToPrintf(error, FROM_HERE,
38 chromeos::errors::json::kDomain,
Alex Vakulenkob04936f2014-09-19 14:53:58 -070039 chromeos::errors::json::kParseError,
40 "Error parsing content of JSON file '%s': %s",
41 json_file_path.value().c_str(),
42 error_message.c_str());
43 return result;
44 }
45 const base::DictionaryValue* dict_value = nullptr;
46 if (!value->GetAsDictionary(&dict_value)) {
47 delete value;
Alex Vakulenkoac8037d2014-11-11 11:42:05 -080048 chromeos::Error::AddToPrintf(error, FROM_HERE,
49 chromeos::errors::json::kDomain,
Alex Vakulenkob04936f2014-09-19 14:53:58 -070050 chromeos::errors::json::kObjectExpected,
51 "Content of file '%s' is not a JSON object",
52 json_file_path.value().c_str());
53 return result;
54 }
55 result.reset(dict_value);
56 return result;
57}
58
59} // namespace buffet