ENH: support default/alternate values for env-vars in dictionary lookup

- was previously only within string expansions, but cover dictionaries
  as well for consistency

ENH: replace the never-used fileName::caseName() functionality

- stringOps::inplaceReplaceVar() is more general

     stringOps::inplaceReplaceVar(myfile, "FOAM_CASE");

STYLE: relax parameter passing when calling some POSIX 'query' functions.

- A std::string is sufficient since the functions use a plain C-string.
  Eg, getEnv("SOMETHING").
  Retain more stringent Foam::word for things like setEnv, since this
  could be useful.
This commit is contained in:
Mark Olesen
2017-02-24 17:37:48 +01:00
parent 49d0b7552e
commit 9810c68e76
7 changed files with 134 additions and 114 deletions

View File

@ -96,13 +96,13 @@ pid_t Foam::pgid()
} }
bool Foam::env(const word& envName) bool Foam::env(const std::string& envName)
{ {
return ::getenv(envName.c_str()) != nullptr; return ::getenv(envName.c_str()) != nullptr;
} }
Foam::string Foam::getEnv(const word& envName) Foam::string Foam::getEnv(const std::string& envName)
{ {
char* env = ::getenv(envName.c_str()); char* env = ::getenv(envName.c_str());
@ -126,7 +126,7 @@ bool Foam::setEnv
const bool overwrite const bool overwrite
) )
{ {
return setenv(envName.c_str(), value.c_str(), overwrite) == 0; return ::setenv(envName.c_str(), value.c_str(), overwrite) == 0;
} }
@ -215,7 +215,7 @@ Foam::fileName Foam::home()
} }
Foam::fileName Foam::home(const string& userName) Foam::fileName Foam::home(const std::string& userName)
{ {
struct passwd* pw; struct passwd* pw;
@ -252,13 +252,13 @@ Foam::fileName Foam::cwd()
List<char> path(pathLengthLimit); List<char> path(pathLengthLimit);
// Resize path if getcwd fails with an ERANGE error // Resize path if getcwd fails with an ERANGE error
while(pathLengthLimit == path.size()) while (pathLengthLimit == path.size())
{ {
if (::getcwd(path.data(), path.size())) if (::getcwd(path.data(), path.size()))
{ {
return path.data(); return path.data();
} }
else if(errno == ERANGE) else if (errno == ERANGE)
{ {
// Increment path length upto the pathLengthMax limit // Increment path length upto the pathLengthMax limit
if if
@ -888,7 +888,7 @@ bool Foam::rm(const fileName& file)
} }
// Try returning plain file name; if not there, try with .gz // Try returning plain file name; if not there, try with .gz
if (remove(file.c_str()) == 0) if (::remove(file.c_str()) == 0)
{ {
return true; return true;
} }
@ -998,7 +998,7 @@ void Foam::fdClose(const int fd)
bool Foam::ping bool Foam::ping
( (
const string& destName, const std::string& destName,
const label destPort, const label destPort,
const label timeOut const label timeOut
) )
@ -1074,9 +1074,9 @@ bool Foam::ping
} }
bool Foam::ping(const string& hostname, const label timeOut) bool Foam::ping(const std::string& host, const label timeOut)
{ {
return ping(hostname, 222, timeOut) || ping(hostname, 22, timeOut); return ping(host, 222, timeOut) || ping(host, 22, timeOut);
} }

View File

@ -3,7 +3,7 @@
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | \\ / O peration |
\\ / A nd | Copyright (C) 2011-2016 OpenFOAM Foundation \\ / A nd | Copyright (C) 2011-2016 OpenFOAM Foundation
\\/ M anipulation | Copyright (C) 2016 OpenCFD Ltd. \\/ M anipulation | Copyright (C) 2016-2017 OpenCFD Ltd.
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
License License
This file is part of OpenFOAM. This file is part of OpenFOAM.
@ -58,11 +58,11 @@ pid_t ppid();
pid_t pgid(); pid_t pgid();
//- Return true if environment variable of given name is defined //- Return true if environment variable of given name is defined
bool env(const word&); bool env(const std::string& envName);
//- Return environment variable of given name //- Return environment variable of given name
// Return string() if the environment is undefined // Return string() if the environment is undefined
string getEnv(const word&); string getEnv(const std::string& envName);
//- Set an environment variable //- Set an environment variable
bool setEnv(const word& name, const std::string& value, const bool overwrite); bool setEnv(const word& name, const std::string& value, const bool overwrite);
@ -84,7 +84,7 @@ bool isAdministrator();
fileName home(); fileName home();
//- Return home directory path name for a particular user //- Return home directory path name for a particular user
fileName home(const string& userName); fileName home(const std::string& userName);
//- Return current working directory path name //- Return current working directory path name
fileName cwd(); fileName cwd();
@ -176,10 +176,10 @@ unsigned int sleep(const unsigned int);
void fdClose(const int); void fdClose(const int);
//- Check if machine is up by pinging given port //- Check if machine is up by pinging given port
bool ping(const string&, const label port, const label timeOut); bool ping(const std::string& destName, const label port, const label timeOut);
//- Check if machine is up by pinging port 22 (ssh) and 222 (rsh) //- Check if machine is up by pinging port 22 (ssh) and 222 (rsh)
bool ping(const string&, const label timeOut=10); bool ping(const std::string& host, const label timeOut=10);
//- Execute the specified command via the shell. //- Execute the specified command via the shell.
// Uses vfork/execl internally. // Uses vfork/execl internally.

View File

@ -228,25 +228,6 @@ Foam::word Foam::fileName::name() const
} }
Foam::string Foam::fileName::caseName() const
{
string cName = *this;
const string caseStr(getEnv("FOAM_CASE"));
const size_type i = find(caseStr);
if (i == npos)
{
return cName;
}
else
{
return cName.replace(i, caseStr.size(), string("$FOAM_CASE"));
}
}
Foam::word Foam::fileName::name(const bool noExt) const Foam::word Foam::fileName::name(const bool noExt) const
{ {
if (noExt) if (noExt)

View File

@ -189,9 +189,6 @@ public:
// //
word name() const; word name() const;
//- Return file name (part beyond last /), subsitute for FOAM_CASE
string caseName() const;
//- Return file name, optionally without extension //- Return file name, optionally without extension
word name(const bool noExt) const; word name(const bool noExt) const;

View File

@ -3,7 +3,7 @@
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | \\ / O peration |
\\ / A nd | Copyright (C) 2011-2016 OpenFOAM Foundation \\ / A nd | Copyright (C) 2011-2016 OpenFOAM Foundation
\\/ M anipulation | \\/ M anipulation | Copyright (C) 2017 OpenCFD Ltd.
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
License License
This file is part of OpenFOAM. This file is part of OpenFOAM.
@ -34,7 +34,6 @@ License
//! \cond fileScope //! \cond fileScope
// Find the type/position of the ":-" or ":+" alternative values // Find the type/position of the ":-" or ":+" alternative values
//
static inline int findParameterAlternative static inline int findParameterAlternative
( (
const std::string& s, const std::string& s,
@ -132,7 +131,7 @@ Foam::string& Foam::stringOps::inplaceExpand
iter != s.end() iter != s.end()
&& &&
( (
isalnum(*iter) std::isalnum(*iter)
|| *iter == '.' || *iter == '.'
|| *iter == ':' || *iter == ':'
|| *iter == '_' || *iter == '_'
@ -285,6 +284,30 @@ Foam::string Foam::stringOps::getVariable
{ {
value = getEnv(name); value = getEnv(name);
if (value.empty() && !name.empty())
{
// The type/position of the ":-" or ":+" alternative values
string::size_type altPos = 0;
// check for parameter:-word or parameter:+word
int altType = findParameterAlternative(name, altPos, name.size()-1);
if (altType)
{
value = getEnv
(
// var-name
word(name.substr(0, altPos), false)
);
// ":-" or ":+" alternative value
if (value.empty() ? (altType == '-') : (altType == '+'))
{
// alternative
value = name.substr(altPos + 2);
}
}
}
if (value.empty()) if (value.empty())
{ {
FatalIOErrorInFunction FatalIOErrorInFunction
@ -391,15 +414,15 @@ Foam::string& Foam::stringOps::inplaceExpand
else else
{ {
string::iterator iter = s.begin() + begVar + 1; string::iterator iter = s.begin() + begVar + 1;
string::size_type endVar = begVar;
// more generous in accepting keywords than for env variables // more generous in accepting keywords than for env variables
string::size_type endVar = begVar;
while while
( (
iter != s.end() iter != s.end()
&& &&
( (
isalnum(*iter) std::isalnum(*iter)
|| *iter == '.' || *iter == '.'
|| *iter == ':' || *iter == ':'
|| *iter == '_' || *iter == '_'
@ -536,7 +559,7 @@ Foam::string& Foam::stringOps::inplaceExpand
iter != s.end() iter != s.end()
&& &&
( (
isalnum(*iter) std::isalnum(*iter)
|| *iter == '.' || *iter == '.'
|| *iter == ':' || *iter == ':'
|| *iter == '_' || *iter == '_'
@ -681,7 +704,7 @@ Foam::string& Foam::stringOps::inplaceExpand
while while
( (
iter != s.end() iter != s.end()
&& (isalnum(*iter) || *iter == '_') && (std::isalnum(*iter) || *iter == '_')
) )
{ {
++iter; ++iter;
@ -843,12 +866,38 @@ Foam::string& Foam::stringOps::inplaceExpand
} }
bool Foam::stringOps::inplaceReplaceVar(string& s, const word& varName)
{
if (s.empty() || varName.empty())
{
return false;
}
const string content(getEnv(varName));
if (content.empty())
{
return false;
}
const std::string::size_type i = s.find(content);
if (i == std::string::npos)
{
return false;
}
else
{
s.replace(i, content.size(), string("${" + varName + "}"));
return true;
}
}
Foam::string Foam::stringOps::trimLeft(const string& s) Foam::string Foam::stringOps::trimLeft(const string& s)
{ {
if (!s.empty()) if (!s.empty())
{ {
string::size_type beg = 0; string::size_type beg = 0;
while (beg < s.size() && isspace(s[beg])) while (beg < s.size() && std::isspace(s[beg]))
{ {
++beg; ++beg;
} }
@ -868,7 +917,7 @@ Foam::string& Foam::stringOps::inplaceTrimLeft(string& s)
if (!s.empty()) if (!s.empty())
{ {
string::size_type beg = 0; string::size_type beg = 0;
while (beg < s.size() && isspace(s[beg])) while (beg < s.size() && std::isspace(s[beg]))
{ {
++beg; ++beg;
} }
@ -888,7 +937,7 @@ Foam::string Foam::stringOps::trimRight(const string& s)
if (!s.empty()) if (!s.empty())
{ {
string::size_type sz = s.size(); string::size_type sz = s.size();
while (sz && isspace(s[sz-1])) while (sz && std::isspace(s[sz-1]))
{ {
--sz; --sz;
} }
@ -908,7 +957,7 @@ Foam::string& Foam::stringOps::inplaceTrimRight(string& s)
if (!s.empty()) if (!s.empty())
{ {
string::size_type sz = s.size(); string::size_type sz = s.size();
while (sz && isspace(s[sz-1])) while (sz && std::isspace(s[sz-1]))
{ {
--sz; --sz;
} }

View File

@ -3,7 +3,7 @@
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | \\ / O peration |
\\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation \\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation
\\/ M anipulation | Copyright (C) 2016 OpenCFD Ltd. \\/ M anipulation | Copyright (C) 2016-2017 OpenCFD Ltd.
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
License License
This file is part of OpenFOAM. This file is part of OpenFOAM.
@ -56,30 +56,26 @@ namespace stringOps
// -# variables // -# variables
// - "$VAR", "${VAR}" // - "$VAR", "${VAR}"
// //
// Supports default values as per the Bourne/Korn shell. // Supports default and alternative values as per the POSIX shell.
// \code // \code
// "${parameter:-defValue}" // a) "${parameter:-defValue}"
// b) "${parameter:+altValue}"
// \endcode // \endcode
// If parameter is unset or null, the \c defValue is substituted. // a) If parameter is unset or null, the \c defValue is substituted.
// Otherwise, the value of parameter is substituted. // Otherwise, the value of parameter is substituted.
// //
// Supports alternative values as per the Bourne/Korn shell. // b) If parameter is unset or null, nothing is substituted.
// \code
// "${parameter:+altValue}"
// \endcode
// If parameter is unset or null, nothing is substituted.
// Otherwise the \c altValue is substituted. // Otherwise the \c altValue is substituted.
// //
// Any unknown entries are removed silently. // - Any unknown entries are removed silently.
// // - Malformed entries (eg, brace mismatch, sigil followed by bad chars)
// Malformed entries (eg, brace mismatch, sigil followed by bad character)
// are left as is. // are left as is.
// //
// \note the leading sigil can be changed to avoid conflicts with other // \note the leading sigil can be changed to avoid conflicts with other
// string expansions // string expansions
string expand string expand
( (
const string&, const string& original,
const HashTable<string, word, string::hash>& mapping, const HashTable<string, word, string::hash>& mapping,
const char sigil = '$' const char sigil = '$'
); );
@ -90,30 +86,26 @@ namespace stringOps
// -# variables // -# variables
// - "$VAR", "${VAR}" // - "$VAR", "${VAR}"
// //
// Supports default values as per the Bourne/Korn shell. // Supports default and alternative values as per the POSIX shell.
// \code // \code
// "${parameter:-defValue}" // a) "${parameter:-defValue}"
// b) "${parameter:+altValue}"
// \endcode // \endcode
// If parameter is unset or null, the \c defValue is substituted. // a) If parameter is unset or null, the \c defValue is substituted.
// Otherwise, the value of parameter is substituted. // Otherwise, the value of parameter is substituted.
// //
// Supports alternative values as per the Bourne/Korn shell. // b) If parameter is unset or null, nothing is substituted.
// \code
// "${parameter:+altValue}"
// \endcode
// If parameter is unset or null, nothing is substituted.
// Otherwise the \c altValue is substituted. // Otherwise the \c altValue is substituted.
// //
// Any unknown entries are removed silently. // - Any unknown entries are removed silently.
// // - Malformed entries (eg, brace mismatch, sigil followed by bad chars)
// Malformed entries (eg, brace mismatch, sigil followed by bad character)
// are left as is. // are left as is.
// //
// \note the leading sigil can be changed to avoid conflicts with other // \note the leading sigil can be changed to avoid conflicts with other
// string expansions // string expansions
string& inplaceExpand string& inplaceExpand
( (
string&, string& s,
const HashTable<string, word, string::hash>& mapping, const HashTable<string, word, string::hash>& mapping,
const char sigil = '$' const char sigil = '$'
); );
@ -129,13 +121,20 @@ namespace stringOps
// string expansions // string expansions
string expand string expand
( (
const string&, const string& original,
const dictionary& dict, const dictionary& dict,
const char sigil = '$' const char sigil = '$'
); );
//- Get dictionary or (optionally) environment variable //- Get dictionary or (optionally) environment variable
//
// The environment variable lookup supports default and alternative
// values as per the POSIX shell.
// \code
// ${parameter:-defValue}
// ${parameter:+altValue}
// \endcode
string getVariable string getVariable
( (
const word& name, const word& name,
@ -189,7 +188,7 @@ namespace stringOps
// string expansions // string expansions
string& inplaceExpand string& inplaceExpand
( (
string&, string& s,
const dictionary& dict, const dictionary& dict,
const char sigil = '$' const char sigil = '$'
); );
@ -206,30 +205,26 @@ namespace stringOps
// - leading "~user" : home directory for specified user // - leading "~user" : home directory for specified user
// - leading "~OpenFOAM" : site/user OpenFOAM configuration directory // - leading "~OpenFOAM" : site/user OpenFOAM configuration directory
// //
// Supports default values as per the Bourne/Korn shell. // Supports default and alternative values as per the POSIX shell.
// \code // \code
// "${parameter:-defValue}" // a) "${parameter:-defValue}"
// b) "${parameter:+altValue}"
// \endcode // \endcode
// If parameter is unset or null, the \c defValue is substituted. // a) If parameter is unset or null, the \c defValue is substituted.
// Otherwise, the value of parameter is substituted. // Otherwise, the value of parameter is substituted.
// //
// Supports alternative values as per the Bourne/Korn shell. // b) If parameter is unset or null, nothing is substituted.
// \code
// "${parameter:+altValue}"
// \endcode
// If parameter is unset or null, nothing is substituted.
// Otherwise the \c altValue is substituted. // Otherwise the \c altValue is substituted.
// //
// Any unknown entries are removed silently, if allowEmpty is true. // - Any unknown entries are removed silently, if allowEmpty is true.
// // - Malformed entries (eg, brace mismatch, sigil followed by bad chars)
// Malformed entries (eg, brace mismatch, sigil followed by bad character)
// are left as is. // are left as is.
// //
// \sa // \sa
// Foam::findEtcFile // Foam::findEtcFile
string expand string expand
( (
const string&, const string& original,
const bool allowEmpty = false const bool allowEmpty = false
); );
@ -245,63 +240,62 @@ namespace stringOps
// - leading "~user" : home directory for specified user // - leading "~user" : home directory for specified user
// - leading "~OpenFOAM" : site/user OpenFOAM configuration directory // - leading "~OpenFOAM" : site/user OpenFOAM configuration directory
// //
// Supports default values as per the Bourne/Korn shell. // Supports default and alternative values as per the POSIX shell.
// \code // \code
// "${parameter:-defValue}" // a) "${parameter:-defValue}"
// b) "${parameter:+altValue}"
// \endcode // \endcode
// If parameter is unset or null, the \c defValue is substituted. // a) If parameter is unset or null, the \c defValue is substituted.
// Otherwise, the value of parameter is substituted. // Otherwise, the value of parameter is substituted.
// //
// Supports alternative values as per the Bourne/Korn shell. // b) If parameter is unset or null, nothing is substituted.
// \code
// "${parameter:+altValue}"
// \endcode
// If parameter is unset or null, nothing is substituted.
// Otherwise the \c altValue is substituted. // Otherwise the \c altValue is substituted.
// //
// Any unknown entries are removed silently, if allowEmpty is true. // - Any unknown entries are removed silently if allowEmpty is true.
// // - Malformed entries (eg, brace mismatch, sigil followed by bad chars)
// Malformed entries (eg, brace mismatch, sigil followed by bad character)
// are left as is. // are left as is.
// //
// Any unknown entries are removed silently if allowEmpty is true.
// \sa // \sa
// Foam::findEtcFile // Foam::findEtcFile
string& inplaceExpand string& inplaceExpand
( (
string&, string& s,
const bool allowEmpty = false const bool allowEmpty = false
); );
//- Replace environment variable contents with its name.
// This is essentially the inverse operation for inplaceExpand.
// Return true if a replacement was successful.
bool inplaceReplaceVar(string& s, const word& varName);
//- Return string trimmed of leading whitespace //- Return string trimmed of leading whitespace
string trimLeft(const string&); string trimLeft(const string& s);
//- Trim leading whitespace inplace //- Trim leading whitespace inplace
string& inplaceTrimLeft(string&); string& inplaceTrimLeft(string& s);
//- Return string trimmed of trailing whitespace //- Return string trimmed of trailing whitespace
string trimRight(const string&); string trimRight(const string& s);
//- Trim trailing whitespace inplace //- Trim trailing whitespace inplace
string& inplaceTrimRight(string&); string& inplaceTrimRight(string& s);
//- Return string trimmed of leading and trailing whitespace //- Return string trimmed of leading and trailing whitespace
string trim(const string&); string trim(const string& original);
//- Trim leading and trailing whitespace inplace //- Trim leading and trailing whitespace inplace
string& inplaceTrim(string&); string& inplaceTrim(string& s);
//- Return a word representation of the primitive, //- Using printf-formatter for a word representation of the primitive.
// using printf-style formatter.
// The representation is not checked for valid word characters - // The representation is not checked for valid word characters -
// it is assumed that the caller knows what they are doing // it is assumed that the caller knows what they are doing
template<class PrimitiveType> template<class PrimitiveType>
Foam::word name(const char* fmt, const PrimitiveType& val); Foam::word name(const char* fmt, const PrimitiveType& val);
//- Return a word representation of the primitive, //- Using printf-formatter for a word representation of the primitive.
// using printf-style formatter.
// The representation is not checked for valid word characters - // The representation is not checked for valid word characters -
// it is assumed that the caller knows what they are doing // it is assumed that the caller knows what they are doing
template<class PrimitiveType> template<class PrimitiveType>

View File

@ -40,15 +40,14 @@ Foam::word Foam::stringOps::name
// same concept as GNU/BSD asprintf() // same concept as GNU/BSD asprintf()
// use snprintf with zero to determine the number of characters required // use snprintf with zero to determine the number of characters required
int n = ::snprintf(0, 0, fmt, val); const int n = ::snprintf(nullptr, 0, fmt, val);
if (n > 0) if (n > 0)
{ {
char buf[n+1]; char buf[n+1];
::snprintf(buf, n+1, fmt, val); ::snprintf(buf, n+1, fmt, val);
buf[n] = 0; buf[n] = 0;
// no stripping desired return word(buf, false); // no stripping desired
return word(buf, false);
} }
return word::null; return word::null;