blob: 39f5908d6b719ddbd00b3fccbe6fb4c80578f080 [file] [log] [blame]
Darin Petkov30030592010-07-27 13:53:20 -07001// 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
12using std::string;
13
14namespace chromeos_update_engine {
15
Darin Petkov1cbd78f2010-07-29 12:38:34 -070016const char kPrefsLastActivePingDay[] = "last-active-ping-day";
17const char kPrefsLastRollCallPingDay[] = "last-roll-call-ping-day";
18
Darin Petkov30030592010-07-27 13:53:20 -070019bool Prefs::Init(const FilePath& prefs_dir) {
20 prefs_dir_ = prefs_dir;
21 return true;
22}
23
24bool Prefs::GetString(const string& key, string* value) {
25 LOG(INFO) << "Getting key \"" << key << "\"";
26 FilePath filename;
27 TEST_AND_RETURN_FALSE(GetFileNameForKey(key, &filename));
28 TEST_AND_RETURN_FALSE(file_util::ReadFileToString(filename, value));
29 LOG(INFO) << "Key \"" << key << "\" value \"" << *value << "\"";
30 return true;
31}
32
33bool Prefs::SetString(const std::string& key, const std::string& value) {
34 LOG(INFO) << "Setting key \"" << key << "\" value \"" << value << "\"";
35 FilePath filename;
36 TEST_AND_RETURN_FALSE(GetFileNameForKey(key, &filename));
37 TEST_AND_RETURN_FALSE(file_util::CreateDirectory(filename.DirName()));
38 TEST_AND_RETURN_FALSE(
39 file_util::WriteFile(filename, value.data(), value.size()) ==
40 static_cast<int>(value.size()));
41 return true;
42}
43
44bool Prefs::GetInt64(const string& key, int64_t* value) {
45 string str_value;
46 TEST_AND_RETURN_FALSE(GetString(key, &str_value));
47 TrimWhitespaceASCII(str_value, TRIM_ALL, &str_value);
48 TEST_AND_RETURN_FALSE(StringToInt64(str_value, value));
49 return true;
50}
51
52bool Prefs::SetInt64(const string& key, const int64_t value) {
53 return SetString(key, Int64ToString(value));
54}
55
56bool Prefs::GetFileNameForKey(const std::string& key, FilePath* filename) {
57 // Allows only non-empty keys containing [A-Za-z0-9_-].
58 TEST_AND_RETURN_FALSE(!key.empty());
59 for (size_t i = 0; i < key.size(); ++i) {
60 char c = key.at(i);
61 TEST_AND_RETURN_FALSE(IsAsciiAlpha(c) || IsAsciiDigit(c) ||
62 c == '_' || c == '-');
63 }
64 *filename = prefs_dir_.Append(key);
65 return true;
66}
67
68} // namespace chromeos_update_engine