| 1 | /*++ |
| 2 | |
| 3 | Copyright (c) Microsoft. All rights reserved. |
| 4 | |
| 5 | Module Name: |
| 6 | |
| 7 | OptionParser.cpp |
| 8 | |
| 9 | Abstract: |
| 10 | |
| 11 | Implementation of OptionParser. Handles the non-template error/lookup |
| 12 | primitives that the templated accessors in OptionParser.h call into. |
| 13 | |
| 14 | --*/ |
| 15 | |
| 16 | #include "precomp.h" |
| 17 | #include "OptionParser.h" |
| 18 | |
| 19 | using wsl::shared::Localization; |
| 20 | |
| 21 | namespace wsl::windows::service::wslc { |
| 22 | |
| 23 | OptionParser::OptionParser(const std::map<std::string, std::string>& Options) noexcept : m_options(Options) |
| 24 | { |
| 25 | } |
| 26 | |
| 27 | const std::string* OptionParser::Find(std::string_view Key) |
| 28 | { |
| 29 | const auto it = m_options.find(std::string(Key)); |
| 30 | if (it == m_options.end()) |
| 31 | { |
| 32 | return nullptr; |
| 33 | } |
| 34 | |
| 35 | m_consumed.insert(it->first); |
| 36 | return &it->second; |
| 37 | } |
| 38 | |
| 39 | std::optional<bool> OptionParser::OptionalBool(std::string_view Key) |
| 40 | { |
| 41 | const auto* value = Find(Key); |
| 42 | if (value == nullptr) |
| 43 | { |
| 44 | return std::nullopt; |
| 45 | } |
| 46 | |
| 47 | const auto parsed = wsl::shared::string::ParseBool(value->c_str()); |
| 48 | if (!parsed.has_value()) |
| 49 | { |
| 50 | ThrowInvalid(Key, *value); |
| 51 | } |
| 52 | |
| 53 | return parsed; |
| 54 | } |
| 55 | |
| 56 | void OptionParser::RejectUnknown() |
| 57 | { |
| 58 | for (const auto& [key, value] : m_options) |
| 59 | { |
| 60 | if (m_consumed.find(key) == m_consumed.end()) |
| 61 | { |
| 62 | ThrowUnknown(key); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | void OptionParser::ThrowInvalid(std::string_view Key, const std::string& Value) |
| 68 | { |
| 69 | THROW_HR_WITH_USER_ERROR(E_INVALIDARG, Localization::MessageWslcInvalidVolumeOption(std::string(Key), Value)); |
| 70 | } |
| 71 | |
| 72 | void OptionParser::ThrowMissing(std::string_view Key) |
| 73 | { |
| 74 | THROW_HR_WITH_USER_ERROR(E_INVALIDARG, Localization::MessageWslcMissingVolumeOption(std::string(Key))); |
| 75 | } |
| 76 | |
| 77 | void OptionParser::ThrowUnknown(std::string_view Key) |
| 78 | { |
| 79 | THROW_HR_WITH_USER_ERROR(E_INVALIDARG, Localization::MessageWslcUnknownVolumeOption(std::string(Key))); |
| 80 | } |
| 81 | |
| 82 | } // namespace wsl::windows::service::wslc |