Home | History | Annotate | Download | only in brillo
      1 // 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 <brillo/osrelease_reader.h>
      6 
      7 #include <base/files/file_enumerator.h>
      8 #include <base/files/file_util.h>
      9 #include <base/logging.h>
     10 #include <brillo/strings/string_utils.h>
     11 
     12 namespace brillo {
     13 
     14 void OsReleaseReader::Load() {
     15   Load(base::FilePath("/"));
     16 }
     17 
     18 bool OsReleaseReader::GetString(const std::string& key,
     19                                 std::string* value) const {
     20   CHECK(initialized_) << "OsReleaseReader.Load() must be called first.";
     21   return store_.GetString(key, value);
     22 }
     23 
     24 void OsReleaseReader::LoadTestingOnly(const base::FilePath& root_dir) {
     25   Load(root_dir);
     26 }
     27 
     28 void OsReleaseReader::Load(const base::FilePath& root_dir) {
     29   base::FilePath osrelease = root_dir.Append("etc").Append("os-release");
     30   if (!store_.Load(osrelease)) {
     31     // /etc/os-release might not be present (cros deploying a new configuration
     32     // or no fields set at all). Just print a debug message and continue.
     33     DLOG(INFO) << "Could not load fields from " << osrelease.value();
     34   }
     35 
     36   base::FilePath osreleased = root_dir.Append("etc").Append("os-release.d");
     37   base::FileEnumerator enumerator(
     38       osreleased, false, base::FileEnumerator::FILES);
     39 
     40   for (base::FilePath path = enumerator.Next(); !path.empty();
     41        path = enumerator.Next()) {
     42     std::string content;
     43     if (!base::ReadFileToString(path, &content)) {
     44       // The only way to fail is if a file exist in /etc/os-release.d but we
     45       // cannot read it.
     46       PLOG(FATAL) << "Could not read " << path.value();
     47     }
     48     // There might be a trailing new line. Strip it to keep only the first line
     49     // of the file.
     50     content = brillo::string_utils::SplitAtFirst(content, "\n", true).first;
     51     store_.SetString(path.BaseName().value(), content);
     52   }
     53   initialized_ = true;
     54 }
     55 
     56 }  // namespace brillo
     57