1// Copyright (c) 2011 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 "chrome/installer/util/app_commands.h"
6
7#include "base/logging.h"
8#include "base/win/registry.h"
9#include "chrome/installer/util/google_update_constants.h"
10#include "chrome/installer/util/work_item_list.h"
11
12using base::win::RegKey;
13
14namespace installer {
15
16AppCommands::AppCommands() {
17}
18
19AppCommands::~AppCommands() {
20}
21
22bool AppCommands::Initialize(const base::win::RegKey& key) {
23  if (!key.Valid()) {
24    LOG(DFATAL) << "Cannot initialize AppCommands from an invalid key.";
25    return false;
26  }
27
28  using base::win::RegistryKeyIterator;
29  static const wchar_t kEmptyString[] = L"";
30
31  commands_.clear();
32
33  RegKey cmd_key;
34  LONG result;
35  AppCommand command;
36  for (RegistryKeyIterator key_iterator(key.Handle(), kEmptyString);
37       key_iterator.Valid(); ++key_iterator) {
38    const wchar_t* name = key_iterator.Name();
39    result = cmd_key.Open(key.Handle(), name, KEY_QUERY_VALUE);
40    if (result != ERROR_SUCCESS) {
41      LOG(ERROR) << "Failed to open key \"" << name
42                 << "\" with last-error code " << result;
43    } else if (command.Initialize(cmd_key)) {
44      commands_[name] = command;
45    } else {
46      VLOG(1) << "Skipping over key \"" << name
47              << "\" as it does not appear to hold a product command.";
48    }
49  }
50
51  return true;
52}
53
54AppCommands& AppCommands::CopyFrom(const AppCommands& other) {
55  commands_ = other.commands_;
56
57  return *this;
58}
59
60void AppCommands::Clear() {
61  commands_.clear();
62}
63
64bool AppCommands::Get(const std::wstring& command_id,
65                      AppCommand* command) const {
66  DCHECK(command);
67  CommandMap::const_iterator it(commands_.find(command_id));
68  if (it == commands_.end())
69    return false;
70  *command = it->second;
71  return true;
72}
73
74bool AppCommands::Set(const std::wstring& command_id,
75                      const AppCommand& command) {
76  std::pair<CommandMap::iterator, bool> result(
77      commands_.insert(std::make_pair(command_id, command)));
78  if (!result.second)
79    result.first->second = command;
80  return result.second;
81}
82
83bool AppCommands::Remove(const std::wstring& command_id) {
84  return commands_.erase(command_id) != 0;
85}
86
87AppCommands::CommandMapRange AppCommands::GetIterators() const {
88  return std::make_pair(commands_.begin(), commands_.end());
89}
90
91}  // namespace installer
92