-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add boost-regex based envsubst implementation
- Loading branch information
Showing
3 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
#ifndef RVSTD_ENVSUBST_HPP | ||
#define RVSTD_ENVSUBST_HPP | ||
|
||
#include <boost/regex.hpp> | ||
|
||
#include <iostream> | ||
#include <regex> | ||
#include <string> | ||
|
||
namespace rvstd { | ||
|
||
auto envsubst(const std::string& text) -> std::string; | ||
|
||
} // namespace rvstd | ||
|
||
#endif // RYJSOND_ENVSUBST_HPP |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
#include "rvstd/envsubst.hpp" | ||
|
||
#include <boost/regex.hpp> | ||
|
||
#include <string> | ||
|
||
namespace rvstd { | ||
|
||
auto envsubst(const std::string& text) -> std::string | ||
{ | ||
static const boost::regex env_var_pattern{R"--(\$(?:(\w+)|\{([^}]+)\}))--"}; | ||
std::ostringstream result; | ||
boost::regex_replace( | ||
std::ostreambuf_iterator<char>(result), | ||
text.begin(), | ||
text.end(), | ||
env_var_pattern, | ||
[&](const boost::match_results<std::string::const_iterator>& match) { | ||
std::string var_name_str; | ||
if(match[1].matched) { | ||
var_name_str = match[1].str(); | ||
} | ||
else if(match[2].matched) { | ||
var_name_str = match[2].str(); | ||
} | ||
if(const char* ptr = std::getenv(var_name_str.c_str()); ptr != nullptr) { | ||
return ptr; | ||
} | ||
return ""; // Empty string for non-existent variables | ||
}); | ||
|
||
return result.str(); // Return the result stored in the output stream | ||
} | ||
|
||
} // namespace rvstd |