fix env variable load and subst order
This commit is contained in:
64
source/src/utils/ordered_env.hpp
Normal file
64
source/src/utils/ordered_env.hpp
Normal file
@@ -0,0 +1,64 @@
|
||||
#ifndef ORDERED_ENV_HPP
|
||||
#define ORDERED_ENV_HPP
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <algorithm>
|
||||
|
||||
namespace dropshell {
|
||||
|
||||
// Type alias for insertion-ordered environment variables
|
||||
using ordered_env_vars = std::vector<std::pair<std::string, std::string>>;
|
||||
|
||||
// Helper functions for working with ordered_env_vars like a map
|
||||
|
||||
// Find a variable by key (returns iterator)
|
||||
inline auto find_var(ordered_env_vars& vars, const std::string& key) {
|
||||
return std::find_if(vars.begin(), vars.end(),
|
||||
[&](const auto& p) { return p.first == key; });
|
||||
}
|
||||
|
||||
inline auto find_var(const ordered_env_vars& vars, const std::string& key) {
|
||||
return std::find_if(vars.begin(), vars.end(),
|
||||
[&](const auto& p) { return p.first == key; });
|
||||
}
|
||||
|
||||
// Get a variable value (returns empty string if not found)
|
||||
inline std::string get_var(const ordered_env_vars& vars, const std::string& key) {
|
||||
auto it = find_var(vars, key);
|
||||
return (it != vars.end()) ? it->second : "";
|
||||
}
|
||||
|
||||
// Set a variable (updates if exists, appends if new)
|
||||
inline void set_var(ordered_env_vars& vars, const std::string& key, const std::string& value) {
|
||||
auto it = find_var(vars, key);
|
||||
if (it != vars.end()) {
|
||||
it->second = value;
|
||||
} else {
|
||||
vars.emplace_back(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if a variable exists
|
||||
inline bool has_var(const ordered_env_vars& vars, const std::string& key) {
|
||||
return find_var(vars, key) != vars.end();
|
||||
}
|
||||
|
||||
// Merge variables from another ordered_env_vars (appends new, skips existing)
|
||||
inline void merge_vars(ordered_env_vars& dest, const ordered_env_vars& src) {
|
||||
for (const auto& [key, value] : src) {
|
||||
if (!has_var(dest, key)) {
|
||||
dest.emplace_back(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clear all variables
|
||||
inline void clear_vars(ordered_env_vars& vars) {
|
||||
vars.clear();
|
||||
}
|
||||
|
||||
} // namespace dropshell
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user