Merge #9494: Introduce an ArgsManager class encapsulating cs_args, mapArgs and mapMultiArgs

78da882 Util: Small improvements in gArgs usage (Jorge Timón)
5292245 Util: Put mapMultiArgs inside ArgsManager (Jorge Timón)
b3cbd55 scripted-diff: Util: Encapsulate mapMultiArgs behind gArgs (Jorge Timón)
f2957ce Util: Create ArgsManager class... (Jorge Timón)

Tree-SHA512: 7d58250da440ad0f41745f46ab6021d6ecbb292035cab3d86fb08ce6bd822df604ac31b3ded6fd6914f7cfd12ba531cbc06a76eb500f629627f47ae6ac8350a7
This commit is contained in:
Wladimir J. van der Laan 2017-05-15 07:30:09 +02:00
commit 41987aa92f
No known key found for this signature in database
GPG key ID: 74810B012346C9A6
7 changed files with 163 additions and 94 deletions

View file

@ -93,9 +93,9 @@ static bool multiUserAuthorized(std::string strUserPass)
std::string strUser = strUserPass.substr(0, strUserPass.find(":")); std::string strUser = strUserPass.substr(0, strUserPass.find(":"));
std::string strPass = strUserPass.substr(strUserPass.find(":") + 1); std::string strPass = strUserPass.substr(strUserPass.find(":") + 1);
if (mapMultiArgs.count("-rpcauth") > 0) { if (gArgs.IsArgSet("-rpcauth")) {
//Search for multi-user login/pass "rpcauth" from config //Search for multi-user login/pass "rpcauth" from config
BOOST_FOREACH(std::string strRPCAuth, mapMultiArgs.at("-rpcauth")) BOOST_FOREACH(std::string strRPCAuth, gArgs.GetArgs("-rpcauth"))
{ {
std::vector<std::string> vFields; std::vector<std::string> vFields;
boost::split(vFields, strRPCAuth, boost::is_any_of(":$")); boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));

View file

@ -196,9 +196,8 @@ static bool InitHTTPAllowList()
LookupHost("::1", localv6, false); LookupHost("::1", localv6, false);
rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
if (mapMultiArgs.count("-rpcallowip")) { if (gArgs.IsArgSet("-rpcallowip")) {
const std::vector<std::string>& vAllow = mapMultiArgs.at("-rpcallowip"); for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
for (std::string strAllow : vAllow) {
CSubNet subnet; CSubNet subnet;
LookupSubNet(strAllow.c_str(), subnet); LookupSubNet(strAllow.c_str(), subnet);
if (!subnet.IsValid()) { if (!subnet.IsValid()) {
@ -321,12 +320,11 @@ static bool HTTPBindAddresses(struct evhttp* http)
if (IsArgSet("-rpcbind")) { if (IsArgSet("-rpcbind")) {
LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n"); LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
} }
} else if (mapMultiArgs.count("-rpcbind")) { // Specific bind address } else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address
const std::vector<std::string>& vbind = mapMultiArgs.at("-rpcbind"); for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
int port = defaultPort; int port = defaultPort;
std::string host; std::string host;
SplitHostPort(*i, port, host); SplitHostPort(strRPCBind, port, host);
endpoints.push_back(std::make_pair(host, port)); endpoints.push_back(std::make_pair(host, port));
} }
} else { // No specific bind address specified, bind to any } else { // No specific bind address specified, bind to any

View file

@ -746,7 +746,7 @@ void InitParameterInteraction()
LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__); LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
} }
if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) { if (gArgs.IsArgSet("-connect")) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default // when only connecting to trusted nodes, do not seed via DNS, or listen by default
if (SoftSetBoolArg("-dnsseed", false)) if (SoftSetBoolArg("-dnsseed", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__); LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
@ -900,8 +900,8 @@ bool AppInitParameterInteraction()
// Make sure enough file descriptors are available // Make sure enough file descriptors are available
int nBind = std::max( int nBind = std::max(
(mapMultiArgs.count("-bind") ? mapMultiArgs.at("-bind").size() : 0) + (gArgs.IsArgSet("-bind") ? gArgs.GetArgs("-bind").size() : 0) +
(mapMultiArgs.count("-whitebind") ? mapMultiArgs.at("-whitebind").size() : 0), size_t(1)); (gArgs.IsArgSet("-whitebind") ? gArgs.GetArgs("-whitebind").size() : 0), size_t(1));
nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS); nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
nMaxConnections = std::max(nUserMaxConnections, 0); nMaxConnections = std::max(nUserMaxConnections, 0);
@ -916,9 +916,9 @@ bool AppInitParameterInteraction()
InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections)); InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
// ********************************************************* Step 3: parameter-to-internal-flags // ********************************************************* Step 3: parameter-to-internal-flags
if (mapMultiArgs.count("-debug") > 0) { if (gArgs.IsArgSet("-debug")) {
// Special-case: if -debug=0/-nodebug is set, turn off debugging messages // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
const std::vector<std::string>& categories = mapMultiArgs.at("-debug"); const std::vector<std::string> categories = gArgs.GetArgs("-debug");
if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) { if (find(categories.begin(), categories.end(), std::string("0")) == categories.end()) {
for (const auto& cat : categories) { for (const auto& cat : categories) {
@ -933,9 +933,8 @@ bool AppInitParameterInteraction()
} }
// Now remove the logging categories which were explicitly excluded // Now remove the logging categories which were explicitly excluded
if (mapMultiArgs.count("-debugexclude") > 0) { if (gArgs.IsArgSet("-debugexclude")) {
const std::vector<std::string>& excludedCategories = mapMultiArgs.at("-debugexclude"); for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
for (const auto& cat : excludedCategories) {
uint32_t flag = 0; uint32_t flag = 0;
if (!GetLogCategory(&flag, &cat)) { if (!GetLogCategory(&flag, &cat)) {
InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat)); InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
@ -1105,15 +1104,14 @@ bool AppInitParameterInteraction()
fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end()); fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
} }
if (mapMultiArgs.count("-bip9params")) { if (gArgs.IsArgSet("-bip9params")) {
// Allow overriding BIP9 parameters for testing // Allow overriding BIP9 parameters for testing
if (!chainparams.MineBlocksOnDemand()) { if (!chainparams.MineBlocksOnDemand()) {
return InitError("BIP9 parameters may only be overridden on regtest."); return InitError("BIP9 parameters may only be overridden on regtest.");
} }
const std::vector<std::string>& deployments = mapMultiArgs.at("-bip9params"); for (const std::string& strDeployment : gArgs.GetArgs("-bip9params")) {
for (auto i : deployments) {
std::vector<std::string> vDeploymentParams; std::vector<std::string> vDeploymentParams;
boost::split(vDeploymentParams, i, boost::is_any_of(":")); boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":"));
if (vDeploymentParams.size() != 3) { if (vDeploymentParams.size() != 3) {
return InitError("BIP9 parameters malformed, expecting deployment:start:end"); return InitError("BIP9 parameters malformed, expecting deployment:start:end");
} }
@ -1259,8 +1257,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// sanitize comments per BIP-0014, format user agent and check total size // sanitize comments per BIP-0014, format user agent and check total size
std::vector<std::string> uacomments; std::vector<std::string> uacomments;
if (mapMultiArgs.count("-uacomment")) { if (gArgs.IsArgSet("-uacomment")) {
BOOST_FOREACH(std::string cmt, mapMultiArgs.at("-uacomment")) BOOST_FOREACH(std::string cmt, gArgs.GetArgs("-uacomment"))
{ {
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt)); return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
@ -1273,9 +1271,9 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
strSubVersion.size(), MAX_SUBVERSION_LENGTH)); strSubVersion.size(), MAX_SUBVERSION_LENGTH));
} }
if (mapMultiArgs.count("-onlynet")) { if (gArgs.IsArgSet("-onlynet")) {
std::set<enum Network> nets; std::set<enum Network> nets;
BOOST_FOREACH(const std::string& snet, mapMultiArgs.at("-onlynet")) { BOOST_FOREACH(const std::string& snet, gArgs.GetArgs("-onlynet")) {
enum Network net = ParseNetwork(snet); enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE) if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
@ -1288,8 +1286,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
} }
} }
if (mapMultiArgs.count("-whitelist")) { if (gArgs.IsArgSet("-whitelist")) {
BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) { BOOST_FOREACH(const std::string& net, gArgs.GetArgs("-whitelist")) {
CSubNet subnet; CSubNet subnet;
LookupSubNet(net.c_str(), subnet); LookupSubNet(net.c_str(), subnet);
if (!subnet.IsValid()) if (!subnet.IsValid())
@ -1350,16 +1348,16 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
if (fListen) { if (fListen) {
bool fBound = false; bool fBound = false;
if (mapMultiArgs.count("-bind")) { if (gArgs.IsArgSet("-bind")) {
BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) { BOOST_FOREACH(const std::string& strBind, gArgs.GetArgs("-bind")) {
CService addrBind; CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(ResolveErrMsg("bind", strBind)); return InitError(ResolveErrMsg("bind", strBind));
fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
} }
} }
if (mapMultiArgs.count("-whitebind")) { if (gArgs.IsArgSet("-whitebind")) {
BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-whitebind")) { BOOST_FOREACH(const std::string& strBind, gArgs.GetArgs("-whitebind")) {
CService addrBind; CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, 0, false)) if (!Lookup(strBind.c_str(), addrBind, 0, false))
return InitError(ResolveErrMsg("whitebind", strBind)); return InitError(ResolveErrMsg("whitebind", strBind));
@ -1368,7 +1366,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST)); fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
} }
} }
if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) { if (!gArgs.IsArgSet("-bind") && !gArgs.IsArgSet("-whitebind")) {
struct in_addr inaddr_any; struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY; inaddr_any.s_addr = INADDR_ANY;
fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE); fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE);
@ -1378,8 +1376,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
} }
if (mapMultiArgs.count("-externalip")) { if (gArgs.IsArgSet("-externalip")) {
BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) { BOOST_FOREACH(const std::string& strAddr, gArgs.GetArgs("-externalip")) {
CService addrLocal; CService addrLocal;
if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid()) if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
AddLocal(addrLocal, LOCAL_MANUAL); AddLocal(addrLocal, LOCAL_MANUAL);
@ -1388,8 +1386,8 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
} }
} }
if (mapMultiArgs.count("-seednode")) { if (gArgs.IsArgSet("-seednode")) {
BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode")) BOOST_FOREACH(const std::string& strDest, gArgs.GetArgs("-seednode"))
connman.AddOneShot(strDest); connman.AddOneShot(strDest);
} }
@ -1615,9 +1613,9 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
uiInterface.NotifyBlockTip.connect(BlockNotifyCallback); uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
std::vector<fs::path> vImportFiles; std::vector<fs::path> vImportFiles;
if (mapMultiArgs.count("-loadblock")) if (gArgs.IsArgSet("-loadblock"))
{ {
BOOST_FOREACH(const std::string& strFile, mapMultiArgs.at("-loadblock")) BOOST_FOREACH(const std::string& strFile, gArgs.GetArgs("-loadblock"))
vImportFiles.push_back(strFile); vImportFiles.push_back(strFile);
} }

View file

@ -1670,12 +1670,12 @@ void CConnman::ProcessOneShot()
void CConnman::ThreadOpenConnections() void CConnman::ThreadOpenConnections()
{ {
// Connect to specific addresses // Connect to specific addresses
if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) if (gArgs.IsArgSet("-connect") && gArgs.GetArgs("-connect").size() > 0)
{ {
for (int64_t nLoop = 0;; nLoop++) for (int64_t nLoop = 0;; nLoop++)
{ {
ProcessOneShot(); ProcessOneShot();
BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-connect")) BOOST_FOREACH(const std::string& strAddr, gArgs.GetArgs("-connect"))
{ {
CAddress addr(CService(), NODE_NONE); CAddress addr(CService(), NODE_NONE);
OpenNetworkConnection(addr, false, NULL, strAddr.c_str()); OpenNetworkConnection(addr, false, NULL, strAddr.c_str());
@ -1877,8 +1877,8 @@ void CConnman::ThreadOpenAddedConnections()
{ {
{ {
LOCK(cs_vAddedNodes); LOCK(cs_vAddedNodes);
if (mapMultiArgs.count("-addnode")) if (gArgs.IsArgSet("-addnode"))
vAddedNodes = mapMultiArgs.at("-addnode"); vAddedNodes = gArgs.GetArgs("-addnode");
} }
while (true) while (true)
@ -2289,7 +2289,7 @@ bool CConnman::Start(CScheduler& scheduler, std::string& strNodeError, Options c
threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this))); threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
// Initiate outbound connections unless connect=0 // Initiate outbound connections unless connect=0
if (!mapMultiArgs.count("-connect") || mapMultiArgs.at("-connect").size() != 1 || mapMultiArgs.at("-connect")[0] != "0") if (!gArgs.IsArgSet("-connect") || gArgs.GetArgs("-connect").size() != 1 || gArgs.GetArgs("-connect")[0] != "0")
threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this))); threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this)));
// Process messages // Process messages

View file

@ -17,8 +17,6 @@
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
extern std::map<std::string, std::string> mapArgs;
BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup) BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(util_criticalsection) BOOST_AUTO_TEST_CASE(util_criticalsection)
@ -100,52 +98,67 @@ BOOST_AUTO_TEST_CASE(util_DateTimeStrFormat)
BOOST_CHECK_EQUAL(DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", 1317425777), "Fri, 30 Sep 2011 23:36:17 +0000"); BOOST_CHECK_EQUAL(DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", 1317425777), "Fri, 30 Sep 2011 23:36:17 +0000");
} }
class TestArgsManager : public ArgsManager
{
public:
std::map<std::string, std::string>& GetMapArgs()
{
return mapArgs;
};
const std::map<std::string, std::vector<std::string> >& GetMapMultiArgs()
{
return mapMultiArgs;
};
};
BOOST_AUTO_TEST_CASE(util_ParseParameters) BOOST_AUTO_TEST_CASE(util_ParseParameters)
{ {
TestArgsManager testArgs;
const char *argv_test[] = {"-ignored", "-a", "-b", "-ccc=argument", "-ccc=multiple", "f", "-d=e"}; const char *argv_test[] = {"-ignored", "-a", "-b", "-ccc=argument", "-ccc=multiple", "f", "-d=e"};
ParseParameters(0, (char**)argv_test); testArgs.ParseParameters(0, (char**)argv_test);
BOOST_CHECK(mapArgs.empty() && mapMultiArgs.empty()); BOOST_CHECK(testArgs.GetMapArgs().empty() && testArgs.GetMapMultiArgs().empty());
ParseParameters(1, (char**)argv_test); testArgs.ParseParameters(1, (char**)argv_test);
BOOST_CHECK(mapArgs.empty() && mapMultiArgs.empty()); BOOST_CHECK(testArgs.GetMapArgs().empty() && testArgs.GetMapMultiArgs().empty());
ParseParameters(5, (char**)argv_test); testArgs.ParseParameters(5, (char**)argv_test);
// expectation: -ignored is ignored (program name argument), // expectation: -ignored is ignored (program name argument),
// -a, -b and -ccc end up in map, -d ignored because it is after // -a, -b and -ccc end up in map, -d ignored because it is after
// a non-option argument (non-GNU option parsing) // a non-option argument (non-GNU option parsing)
BOOST_CHECK(mapArgs.size() == 3 && mapMultiArgs.size() == 3); BOOST_CHECK(testArgs.GetMapArgs().size() == 3 && testArgs.GetMapMultiArgs().size() == 3);
BOOST_CHECK(IsArgSet("-a") && IsArgSet("-b") && IsArgSet("-ccc") BOOST_CHECK(testArgs.IsArgSet("-a") && testArgs.IsArgSet("-b") && testArgs.IsArgSet("-ccc")
&& !IsArgSet("f") && !IsArgSet("-d")); && !testArgs.IsArgSet("f") && !testArgs.IsArgSet("-d"));
BOOST_CHECK(mapMultiArgs.count("-a") && mapMultiArgs.count("-b") && mapMultiArgs.count("-ccc") BOOST_CHECK(testArgs.GetMapMultiArgs().count("-a") && testArgs.GetMapMultiArgs().count("-b") && testArgs.GetMapMultiArgs().count("-ccc")
&& !mapMultiArgs.count("f") && !mapMultiArgs.count("-d")); && !testArgs.GetMapMultiArgs().count("f") && !testArgs.GetMapMultiArgs().count("-d"));
BOOST_CHECK(mapArgs["-a"] == "" && mapArgs["-ccc"] == "multiple"); BOOST_CHECK(testArgs.GetMapArgs()["-a"] == "" && testArgs.GetMapArgs()["-ccc"] == "multiple");
BOOST_CHECK(mapMultiArgs.at("-ccc").size() == 2); BOOST_CHECK(testArgs.GetArgs("-ccc").size() == 2);
} }
BOOST_AUTO_TEST_CASE(util_GetArg) BOOST_AUTO_TEST_CASE(util_GetArg)
{ {
mapArgs.clear(); TestArgsManager testArgs;
mapArgs["strtest1"] = "string..."; testArgs.GetMapArgs().clear();
testArgs.GetMapArgs()["strtest1"] = "string...";
// strtest2 undefined on purpose // strtest2 undefined on purpose
mapArgs["inttest1"] = "12345"; testArgs.GetMapArgs()["inttest1"] = "12345";
mapArgs["inttest2"] = "81985529216486895"; testArgs.GetMapArgs()["inttest2"] = "81985529216486895";
// inttest3 undefined on purpose // inttest3 undefined on purpose
mapArgs["booltest1"] = ""; testArgs.GetMapArgs()["booltest1"] = "";
// booltest2 undefined on purpose // booltest2 undefined on purpose
mapArgs["booltest3"] = "0"; testArgs.GetMapArgs()["booltest3"] = "0";
mapArgs["booltest4"] = "1"; testArgs.GetMapArgs()["booltest4"] = "1";
BOOST_CHECK_EQUAL(GetArg("strtest1", "default"), "string..."); BOOST_CHECK_EQUAL(testArgs.GetArg("strtest1", "default"), "string...");
BOOST_CHECK_EQUAL(GetArg("strtest2", "default"), "default"); BOOST_CHECK_EQUAL(testArgs.GetArg("strtest2", "default"), "default");
BOOST_CHECK_EQUAL(GetArg("inttest1", -1), 12345); BOOST_CHECK_EQUAL(testArgs.GetArg("inttest1", -1), 12345);
BOOST_CHECK_EQUAL(GetArg("inttest2", -1), 81985529216486895LL); BOOST_CHECK_EQUAL(testArgs.GetArg("inttest2", -1), 81985529216486895LL);
BOOST_CHECK_EQUAL(GetArg("inttest3", -1), -1); BOOST_CHECK_EQUAL(testArgs.GetArg("inttest3", -1), -1);
BOOST_CHECK_EQUAL(GetBoolArg("booltest1", false), true); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest1", false), true);
BOOST_CHECK_EQUAL(GetBoolArg("booltest2", false), false); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest2", false), false);
BOOST_CHECK_EQUAL(GetBoolArg("booltest3", false), false); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest3", false), false);
BOOST_CHECK_EQUAL(GetBoolArg("booltest4", false), true); BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest4", false), true);
} }
BOOST_AUTO_TEST_CASE(util_FormatMoney) BOOST_AUTO_TEST_CASE(util_FormatMoney)

View file

@ -13,7 +13,6 @@
#include "fs.h" #include "fs.h"
#include "random.h" #include "random.h"
#include "serialize.h" #include "serialize.h"
#include "sync.h"
#include "utilstrencodings.h" #include "utilstrencodings.h"
#include "utiltime.h" #include "utiltime.h"
@ -92,10 +91,7 @@
const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf"; const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
const char * const BITCOIN_PID_FILENAME = "bitcoind.pid"; const char * const BITCOIN_PID_FILENAME = "bitcoind.pid";
CCriticalSection cs_args; ArgsManager gArgs;
std::map<std::string, std::string> mapArgs;
static std::map<std::string, std::vector<std::string> > _mapMultiArgs;
const std::map<std::string, std::vector<std::string> >& mapMultiArgs = _mapMultiArgs;
bool fPrintToConsole = false; bool fPrintToConsole = false;
bool fPrintToDebugLog = true; bool fPrintToDebugLog = true;
@ -384,11 +380,11 @@ static void InterpretNegativeSetting(std::string& strKey, std::string& strValue)
} }
} }
void ParseParameters(int argc, const char* const argv[]) void ArgsManager::ParseParameters(int argc, const char* const argv[])
{ {
LOCK(cs_args); LOCK(cs_args);
mapArgs.clear(); mapArgs.clear();
_mapMultiArgs.clear(); mapMultiArgs.clear();
for (int i = 1; i < argc; i++) for (int i = 1; i < argc; i++)
{ {
@ -416,17 +412,23 @@ void ParseParameters(int argc, const char* const argv[])
InterpretNegativeSetting(str, strValue); InterpretNegativeSetting(str, strValue);
mapArgs[str] = strValue; mapArgs[str] = strValue;
_mapMultiArgs[str].push_back(strValue); mapMultiArgs[str].push_back(strValue);
} }
} }
bool IsArgSet(const std::string& strArg) std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg)
{
LOCK(cs_args);
return mapMultiArgs.at(strArg);
}
bool ArgsManager::IsArgSet(const std::string& strArg)
{ {
LOCK(cs_args); LOCK(cs_args);
return mapArgs.count(strArg); return mapArgs.count(strArg);
} }
std::string GetArg(const std::string& strArg, const std::string& strDefault) std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault)
{ {
LOCK(cs_args); LOCK(cs_args);
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
@ -434,7 +436,7 @@ std::string GetArg(const std::string& strArg, const std::string& strDefault)
return strDefault; return strDefault;
} }
int64_t GetArg(const std::string& strArg, int64_t nDefault) int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault)
{ {
LOCK(cs_args); LOCK(cs_args);
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
@ -442,7 +444,7 @@ int64_t GetArg(const std::string& strArg, int64_t nDefault)
return nDefault; return nDefault;
} }
bool GetBoolArg(const std::string& strArg, bool fDefault) bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault)
{ {
LOCK(cs_args); LOCK(cs_args);
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
@ -450,16 +452,16 @@ bool GetBoolArg(const std::string& strArg, bool fDefault)
return fDefault; return fDefault;
} }
bool SoftSetArg(const std::string& strArg, const std::string& strValue) bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
{ {
LOCK(cs_args); LOCK(cs_args);
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
return false; return false;
mapArgs[strArg] = strValue; ForceSetArg(strArg, strValue);
return true; return true;
} }
bool SoftSetBoolArg(const std::string& strArg, bool fValue) bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
{ {
if (fValue) if (fValue)
return SoftSetArg(strArg, std::string("1")); return SoftSetArg(strArg, std::string("1"));
@ -467,10 +469,11 @@ bool SoftSetBoolArg(const std::string& strArg, bool fValue)
return SoftSetArg(strArg, std::string("0")); return SoftSetArg(strArg, std::string("0"));
} }
void ForceSetArg(const std::string& strArg, const std::string& strValue) void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
{ {
LOCK(cs_args); LOCK(cs_args);
mapArgs[strArg] = strValue; mapArgs[strArg] = strValue;
mapMultiArgs[strArg].push_back(strValue);
} }
@ -589,7 +592,7 @@ fs::path GetConfigFile(const std::string& confPath)
return pathConfigFile; return pathConfigFile;
} }
void ReadConfigFile(const std::string& confPath) void ArgsManager::ReadConfigFile(const std::string& confPath)
{ {
fs::ifstream streamConfig(GetConfigFile(confPath)); fs::ifstream streamConfig(GetConfigFile(confPath));
if (!streamConfig.good()) if (!streamConfig.good())
@ -608,7 +611,7 @@ void ReadConfigFile(const std::string& confPath)
InterpretNegativeSetting(strKey, strValue); InterpretNegativeSetting(strKey, strValue);
if (mapArgs.count(strKey) == 0) if (mapArgs.count(strKey) == 0)
mapArgs[strKey] = strValue; mapArgs[strKey] = strValue;
_mapMultiArgs[strKey].push_back(strValue); mapMultiArgs[strKey].push_back(strValue);
} }
} }
// If datadir is changed in .conf file: // If datadir is changed in .conf file:

View file

@ -16,6 +16,7 @@
#include "compat.h" #include "compat.h"
#include "fs.h" #include "fs.h"
#include "sync.h"
#include "tinyformat.h" #include "tinyformat.h"
#include "utiltime.h" #include "utiltime.h"
@ -41,7 +42,6 @@ public:
boost::signals2::signal<std::string (const char* psz)> Translate; boost::signals2::signal<std::string (const char* psz)> Translate;
}; };
extern const std::map<std::string, std::vector<std::string> >& mapMultiArgs;
extern bool fPrintToConsole; extern bool fPrintToConsole;
extern bool fPrintToDebugLog; extern bool fPrintToDebugLog;
@ -148,7 +148,6 @@ bool error(const char* fmt, const Args&... args)
} }
void PrintExceptionContinue(const std::exception *pex, const char* pszThread); void PrintExceptionContinue(const std::exception *pex, const char* pszThread);
void ParseParameters(int argc, const char*const argv[]);
void FileCommit(FILE *file); void FileCommit(FILE *file);
bool TruncateFile(FILE *file, unsigned int length); bool TruncateFile(FILE *file, unsigned int length);
int RaiseFileDescriptorLimit(int nMinFD); int RaiseFileDescriptorLimit(int nMinFD);
@ -163,7 +162,6 @@ fs::path GetConfigFile(const std::string& confPath);
fs::path GetPidFile(); fs::path GetPidFile();
void CreatePidFile(const fs::path &path, pid_t pid); void CreatePidFile(const fs::path &path, pid_t pid);
#endif #endif
void ReadConfigFile(const std::string& confPath);
#ifdef WIN32 #ifdef WIN32
fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true); fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
#endif #endif
@ -180,6 +178,16 @@ inline bool IsSwitchChar(char c)
#endif #endif
} }
class ArgsManager
{
protected:
CCriticalSection cs_args;
std::map<std::string, std::string> mapArgs;
std::map<std::string, std::vector<std::string> > mapMultiArgs;
public:
void ParseParameters(int argc, const char*const argv[]);
void ReadConfigFile(const std::string& confPath);
std::vector<std::string> GetArgs(const std::string& strArg);
/** /**
* Return true if the given argument has been manually set * Return true if the given argument has been manually set
* *
@ -235,6 +243,55 @@ bool SoftSetBoolArg(const std::string& strArg, bool fValue);
// Forces a arg setting, used only in testing // Forces a arg setting, used only in testing
void ForceSetArg(const std::string& strArg, const std::string& strValue); void ForceSetArg(const std::string& strArg, const std::string& strValue);
};
extern ArgsManager gArgs;
// wrappers using the global ArgsManager:
static inline void ParseParameters(int argc, const char*const argv[])
{
gArgs.ParseParameters(argc, argv);
}
static inline void ReadConfigFile(const std::string& confPath)
{
gArgs.ReadConfigFile(confPath);
}
static inline bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
return gArgs.SoftSetArg(strArg, strValue);
}
static inline void ForceSetArg(const std::string& strArg, const std::string& strValue)
{
gArgs.ForceSetArg(strArg, strValue);
}
static inline bool IsArgSet(const std::string& strArg)
{
return gArgs.IsArgSet(strArg);
}
static inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
return gArgs.GetArg(strArg, strDefault);
}
static inline int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
return gArgs.GetArg(strArg, nDefault);
}
static inline bool GetBoolArg(const std::string& strArg, bool fDefault)
{
return gArgs.GetBoolArg(strArg, fDefault);
}
static inline bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
return gArgs.SoftSetBoolArg(strArg, fValue);
}
/** /**
* Format a string to be used as group of options in help messages * Format a string to be used as group of options in help messages