blob: fbe7e15dc0cc1f147ac031bbf539ccdbedb86af9 [file] [log] [blame]
Eric Carusocc7106c2017-04-27 14:22:42 -07001// Copyright 2017 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#ifndef DEBUGD_SRC_VARIANT_UTILS_H_
6#define DEBUGD_SRC_VARIANT_UTILS_H_
7
8#include <string>
9#include <brillo/errors/error.h>
Simon Glass2b1da092020-05-21 12:24:16 -060010#include <brillo/process/process.h>
Eric Carusocc7106c2017-04-27 14:22:42 -070011#include <brillo/type_name_undecorate.h>
12#include <brillo/variant_dictionary.h>
13
14#include "debugd/src/error_utils.h"
15#include "debugd/src/process_with_id.h"
16
17namespace debugd {
18
19const char kOptionParsingErrorString[] =
20 "org.chromium.debugd.error.OptionParsing";
21
22enum class ParseResult {
23 NOT_PRESENT,
24 PARSE_ERROR,
25 PARSED,
26};
27
28// Looks up an option in the |options| dictionary. If the
29// option is not present, returns NOT_PRESENT. If parsing
30// fails (i.e. the supplied option is the wrong type) then
31// add to the error chain in |error| and return PARSE_ERROR.
32// If the option is present and of the right type, return
33// PARSED.
34template <typename T>
35ParseResult GetOption(const brillo::VariantDictionary& options,
36 const std::string& key,
37 T* value,
38 brillo::ErrorPtr* error) {
39 DCHECK(value);
40
41 const auto& it = options.find(key);
42 if (it == options.end())
43 return ParseResult::NOT_PRESENT;
44
45 if (!it->second.GetValue(value)) {
46 std::string expected = brillo::GetUndecoratedTypeName<T>();
47 std::string got = it->second.GetUndecoratedTypeName();
Tom Hughesd6c2d392020-08-24 18:12:11 -070048 DEBUGD_ADD_ERROR_FMT(
49 error, kOptionParsingErrorString,
50 "Option \"%s\" has the wrong type (expected %s, got %s)", key.c_str(),
51 expected.c_str(), got.c_str());
Eric Carusocc7106c2017-04-27 14:22:42 -070052 return ParseResult::PARSE_ERROR;
53 }
54 return ParseResult::PARSED;
55}
56
57// Looks up an option in the |options| dictionary. If it exists and
58// isn't an integer, returns false. Otherwise, returns true, and if it
59// exists in the dictionary adds it to the command line for |process|
60// as the value for key |flag_name|.
Nicole Anderson-Aud9f0aed2020-12-22 17:16:25 +000061bool AddIntOption(SandboxedProcess* process,
Eric Carusocc7106c2017-04-27 14:22:42 -070062 const brillo::VariantDictionary& options,
63 const std::string& key,
64 const std::string& flag_name,
65 brillo::ErrorPtr* error);
66
67} // namespace debugd
68
69#endif // DEBUGD_SRC_VARIANT_UTILS_H_