1// Copyright 2014 The Chromium 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 "mojo/tools/package_manager/manifest.h"
6
7#include "base/files/file_util.h"
8#include "base/json/json_reader.h"
9#include "base/values.h"
10#include "url/gurl.h"
11
12namespace mojo {
13
14Manifest::Manifest() {
15}
16
17Manifest::~Manifest() {
18}
19
20bool Manifest::Parse(const std::string& str, std::string* err_msg) {
21  int err_code = base::JSONReader::JSON_NO_ERROR;
22  scoped_ptr<base::Value> root(base::JSONReader::ReadAndReturnError(
23      str,
24      base::JSON_ALLOW_TRAILING_COMMAS,
25      &err_code, err_msg));
26  if (err_code != base::JSONReader::JSON_NO_ERROR)
27    return false;
28
29  const base::DictionaryValue* root_dict;
30  if (!root->GetAsDictionary(&root_dict)) {
31    *err_msg = "Manifest is not a dictionary.";
32    return false;
33  }
34
35  if (!PopulateDeps(root_dict, err_msg))
36    return false;
37
38  return true;
39}
40
41bool Manifest::ParseFromFile(const base::FilePath& file_name,
42                             std::string* err_msg) {
43  std::string data;
44  if (!base::ReadFileToString(file_name, &data)) {
45    *err_msg = "Couldn't read manifest file " + file_name.AsUTF8Unsafe();
46    return false;
47  }
48  return Parse(data, err_msg);
49}
50
51bool Manifest::PopulateDeps(const base::DictionaryValue* root,
52                            std::string* err_msg) {
53  const base::Value* deps_value;
54  if (!root->Get("deps", &deps_value))
55    return true;  // No deps, that's OK.
56
57  const base::ListValue* deps;
58  if (!deps_value->GetAsList(&deps)) {
59    *err_msg = "Deps is not a list. Should be \"deps\": [ \"...\", \"...\" ]";
60    return false;
61  }
62
63  deps_.reserve(deps->GetSize());
64  for (size_t i = 0; i < deps->GetSize(); i++) {
65    std::string cur_dep;
66    if (!deps->GetString(i, &cur_dep)) {
67      *err_msg = "Dependency list item wasn't a string.";
68      return false;
69    }
70
71    GURL cur_url(cur_dep);
72    if (!cur_url.is_valid()) {
73      *err_msg = "Dependency entry isn't a valid URL: " + cur_dep;
74      return false;
75    }
76
77    deps_.push_back(cur_url);
78  }
79
80  return true;
81}
82
83}  // namespace mojo
84