OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2010 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 "update_engine/prefs.h" |
| 6 |
| 7 #include "base/file_util.h" |
| 8 #include "base/logging.h" |
| 9 #include "base/string_util.h" |
| 10 #include "update_engine/utils.h" |
| 11 |
| 12 using std::string; |
| 13 |
| 14 namespace chromeos_update_engine { |
| 15 |
| 16 bool Prefs::Init(const FilePath& prefs_dir) { |
| 17 prefs_dir_ = prefs_dir; |
| 18 return true; |
| 19 } |
| 20 |
| 21 bool Prefs::GetString(const string& key, string* value) { |
| 22 LOG(INFO) << "Getting key \"" << key << "\""; |
| 23 FilePath filename; |
| 24 TEST_AND_RETURN_FALSE(GetFileNameForKey(key, &filename)); |
| 25 TEST_AND_RETURN_FALSE(file_util::ReadFileToString(filename, value)); |
| 26 LOG(INFO) << "Key \"" << key << "\" value \"" << *value << "\""; |
| 27 return true; |
| 28 } |
| 29 |
| 30 bool Prefs::SetString(const std::string& key, const std::string& value) { |
| 31 LOG(INFO) << "Setting key \"" << key << "\" value \"" << value << "\""; |
| 32 FilePath filename; |
| 33 TEST_AND_RETURN_FALSE(GetFileNameForKey(key, &filename)); |
| 34 TEST_AND_RETURN_FALSE(file_util::CreateDirectory(filename.DirName())); |
| 35 TEST_AND_RETURN_FALSE( |
| 36 file_util::WriteFile(filename, value.data(), value.size()) == |
| 37 static_cast<int>(value.size())); |
| 38 return true; |
| 39 } |
| 40 |
| 41 bool Prefs::GetInt64(const string& key, int64_t* value) { |
| 42 string str_value; |
| 43 TEST_AND_RETURN_FALSE(GetString(key, &str_value)); |
| 44 TrimWhitespaceASCII(str_value, TRIM_ALL, &str_value); |
| 45 TEST_AND_RETURN_FALSE(StringToInt64(str_value, value)); |
| 46 return true; |
| 47 } |
| 48 |
| 49 bool Prefs::SetInt64(const string& key, const int64_t value) { |
| 50 return SetString(key, Int64ToString(value)); |
| 51 } |
| 52 |
| 53 bool Prefs::GetFileNameForKey(const std::string& key, FilePath* filename) { |
| 54 // Allows only non-empty keys containing [A-Za-z0-9_-]. |
| 55 TEST_AND_RETURN_FALSE(!key.empty()); |
| 56 for (size_t i = 0; i < key.size(); ++i) { |
| 57 char c = key.at(i); |
| 58 TEST_AND_RETURN_FALSE(IsAsciiAlpha(c) || IsAsciiDigit(c) || |
| 59 c == '_' || c == '-'); |
| 60 } |
| 61 *filename = prefs_dir_.Append(key); |
| 62 return true; |
| 63 } |
| 64 |
| 65 } // namespace chromeos_update_engine |
OLD | NEW |