util/system: Add GetFixedPointArg helper

This commit is contained in:
Luke Dashjr 2023-09-04 22:49:11 +00:00
parent a61291953e
commit d4a481925b
3 changed files with 31 additions and 1 deletions

View File

@ -503,6 +503,25 @@ int64_t SettingToInt(const common::SettingsValue& value, int64_t nDefault)
return SettingToInt(value).value_or(nDefault);
}
std::optional<int64_t> ArgsManager::GetFixedPointArg(const std::string& arg, int decimals) const
{
const common::SettingsValue value = GetSetting(arg);
return SettingToFixedPoint(value, decimals);
}
std::optional<int64_t> SettingToFixedPoint(const common::SettingsValue& value, int decimals)
{
if (value.isNull()) return std::nullopt;
if (value.isFalse()) return 0;
if (value.isTrue()) return 1;
if (!value.isNum()) value.get_str(); // throws an exception if type is wrong
int64_t v;
if (!ParseFixedPoint(value.getValStr(), decimals, &v)) {
throw std::runtime_error(strprintf("Parse error ('%s')", value.getValStr()));
}
return v;
}
bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
{
return GetBoolArg(strArg).value_or(fDefault);

View File

@ -90,6 +90,8 @@ std::optional<std::string> SettingToString(const common::SettingsValue&);
int64_t SettingToInt(const common::SettingsValue&, int64_t);
std::optional<int64_t> SettingToInt(const common::SettingsValue&);
std::optional<int64_t> SettingToFixedPoint(const common::SettingsValue&, int decimals);
bool SettingToBool(const common::SettingsValue&, bool);
std::optional<bool> SettingToBool(const common::SettingsValue&);
@ -293,6 +295,15 @@ protected:
int64_t GetIntArg(const std::string& strArg, int64_t nDefault) const;
std::optional<int64_t> GetIntArg(const std::string& strArg) const;
/**
* Return fixed-point argument
*
* @param arg Argument to get (e.g. "-foo")
* @param decimals Number of fractional decimal digits to accept
* @return Command-line argument (0 if invalid number) multiplied by 10**decimals
*/
std::optional<int64_t> GetFixedPointArg(const std::string& arg, int decimals) const;
/**
* Return boolean argument or default value
*

View File

@ -15,7 +15,7 @@ import re
FOLDER_GREP = 'src'
FOLDER_TEST = 'src/test/'
REGEX_ARG = r'\b(?:GetArg|GetArgs|GetBoolArg|GetIntArg|GetPathArg|IsArgSet|get_net)\("(-[^"]+)"'
REGEX_ARG = r'\b(?:GetArg|GetArgs|GetBoolArg|GetIntArg|GetFixedPointArg|GetPathArg|IsArgSet|get_net)\("(-[^"]+)"'
REGEX_DOC = r'AddArg\("(-[^"=]+?)(?:=|")'
CMD_ROOT_DIR = '$(git rev-parse --show-toplevel)/{}'.format(FOLDER_GREP)
CMD_GREP_ARGS = r"git grep --perl-regexp '{}' -- {} ':(exclude){}'".format(REGEX_ARG, CMD_ROOT_DIR, FOLDER_TEST)