Files
dropshell/source/src/utils/ordered_env.hpp
j af75b0b4ac
All checks were successful
Build-Test-Publish / build (linux/amd64) (push) Successful in 1m24s
Build-Test-Publish / build (linux/arm64) (push) Successful in 4m16s
fix env variable load and subst order
2025-10-03 18:56:04 +13:00

65 lines
1.8 KiB
C++

#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