summaryrefslogtreecommitdiff
path: root/chromium/fuchsia/base/config_reader.cc
blob: 0c73357e93ad3076243d394df6d46d89499abe6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "fuchsia/base/config_reader.h"

#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/no_destructor.h"

namespace cr_fuchsia {

namespace {

base::Optional<base::Value> ReadPackageConfig() {
  constexpr char kConfigPath[] = "/config/data/config.json";

  base::FilePath path(kConfigPath);
  if (!base::PathExists(path)) {
    LOG(WARNING) << "Config file doesn't exist: " << path.value();
    return base::nullopt;
  }

  std::string file_content;
  bool loaded = base::ReadFileToString(path, &file_content);
  if (!loaded) {
    LOG(WARNING) << "Couldn't read config file: " << path.value();
    return base::nullopt;
  }

  base::JSONReader::ValueWithError parsed =
      base::JSONReader::ReadAndReturnValueWithError(file_content);
  CHECK(parsed.value) << "Failed to parse " << path.value() << ": "
                      << parsed.error_message;
  CHECK(parsed.value->is_dict())
      << "Config is not a JSON dictionary: " << path.value();

  return std::move(parsed.value);
}

}  // namespace

const base::Optional<base::Value>& LoadPackageConfig() {
  // Package configurations do not change at run-time, so read the configuration
  // on the first call and cache the result.
  static base::NoDestructor<base::Optional<base::Value>> config(
      ReadPackageConfig());
  return *config;
}

}  // namespace cr_fuchsia