Skip to content

Commit

Permalink
Add boost-regex based envsubst implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
doganulus committed Apr 14, 2024
1 parent a138446 commit 0283601
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ TARGET_SOURCES(
rvstd
PRIVATE
"src/rvstd/boost_json_ext.cpp"
"src/rvstd/envsubst.cpp"
"src/rvstd/unique_identifier.cpp"
"src/rvstd/tableau.cpp"
"src/rvstd/options.cpp"
Expand Down
16 changes: 16 additions & 0 deletions include/rvstd/envsubst.hpp
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
35 changes: 35 additions & 0 deletions src/rvstd/envsubst.cpp
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

0 comments on commit 0283601

Please sign in to comment.