ENH: support default values in string expansion

- syntax as per Bourne/Korn shell
      ${parameter:-defValue}

  If parameter is unset or null, the \c defValue is substituted.
  Otherwise, the value of parameter is substituted.
This commit is contained in:
Mark Olesen
2011-03-02 14:11:30 +01:00
parent 01ea4623f9
commit 3b72fc3e38
3 changed files with 129 additions and 8 deletions

View File

@ -66,10 +66,23 @@ Foam::string& Foam::stringOps::inplaceExpand
string::size_type endVar = begVar;
string::size_type delim = 0;
// The position of the ":-" default value
string::size_type altPos = string::npos;
if (s[begVar+1] == '{')
{
endVar = s.find('}', begVar);
delim = 1;
// looks like ${parameter:-word}
if (endVar != string::npos)
{
altPos = s.find(":-", begVar);
if (altPos != string::npos && altPos > endVar)
{
altPos = string::npos;
}
}
}
else
{
@ -110,11 +123,26 @@ Foam::string& Foam::stringOps::inplaceExpand
s.substr
(
begVar + 1 + delim,
endVar - begVar - 2*delim
(
(altPos == string::npos ? endVar : altPos)
- begVar - 2*delim
)
),
false
);
std::string altValue;
if (altPos != string::npos)
{
// had ":-" default value
altValue = s.substr
(
altPos + 2,
endVar - altPos - 2*delim
);
}
HashTable<string, word, string::hash>::const_iterator fnd =
mapping.find(varName);
@ -128,6 +156,17 @@ Foam::string& Foam::stringOps::inplaceExpand
);
begVar += (*fnd).size();
}
else if (altPos != string::npos)
{
// use alternative provided
s.std::string::replace
(
begVar,
endVar - begVar + 1,
altValue
);
begVar += altValue.size();
}
else
{
s.std::string::replace
@ -312,10 +351,23 @@ Foam::string& Foam::stringOps::inplaceExpand
string::size_type endVar = begVar;
string::size_type delim = 0;
// The position of the ":-" default value
string::size_type altPos = string::npos;
if (s[begVar+1] == '{')
{
endVar = s.find('}', begVar);
delim = 1;
// looks like ${parameter:-word}
if (endVar != string::npos)
{
altPos = s.find(":-", begVar);
if (altPos != string::npos && altPos > endVar)
{
altPos = string::npos;
}
}
}
else
{
@ -350,11 +402,25 @@ Foam::string& Foam::stringOps::inplaceExpand
s.substr
(
begVar + 1 + delim,
endVar - begVar - 2*delim
(
(altPos == string::npos ? endVar : altPos)
- begVar - 2*delim
)
),
false
);
std::string altValue;
if (altPos != string::npos)
{
// had ":-" default value
altValue = s.substr
(
altPos + 2,
endVar - altPos - 2*delim
);
}
const string varValue = getEnv(varName);
if (varValue.size())
{
@ -367,6 +433,17 @@ Foam::string& Foam::stringOps::inplaceExpand
);
begVar += varValue.size();
}
else if (altPos != string::npos)
{
// use alternative provided
s.std::string::replace
(
begVar,
endVar - begVar + 1,
altValue
);
begVar += altValue.size();
}
else if (allowEmpty)
{
s.std::string::replace