Skip to content

Commit

Permalink
Sort the environment variables
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Carroll <[email protected]>
  • Loading branch information
mjcarroll committed Nov 1, 2023
1 parent 65f81d7 commit 55451cc
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/Environment.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@

#include <gz/utils/Environment.hh>

#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>

extern char ** environ;

Expand Down Expand Up @@ -165,7 +167,13 @@ bool setenv(const EnvironmentMap &_vars)
std::string printenv()
{
std::string ret;
for (const auto &[key, value] : env())
// Variables are in an unordered_map as we generally don't
// care, but for printing sort for consistent display
auto currentEnv = env();
auto sorted = std::vector<std::pair<std::string, std::string>>(
currentEnv.begin(), currentEnv.end());
std::sort(sorted.begin(), sorted.end());
for (const auto &[key, value] : sorted)
{
ret.append(key);
ret.append("=");
Expand Down
3 changes: 2 additions & 1 deletion src/Environment_TEST.cc
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ TEST(Environment, printenv)
ASSERT_TRUE(gz::utils::setenv("GZ_BAR_KEY", "GZ_BAR_VAL"));
ASSERT_TRUE(gz::utils::setenv("GZ_BAZ_KEY", "GZ_BAZ_VAL"));

// Always returned in sorted order
EXPECT_EQ(gz::utils::printenv(),
"GZ_BAZ_KEY=GZ_BAZ_VAL\nGZ_BAR_KEY=GZ_BAR_VAL\nGZ_FOO_KEY=GZ_FOO_VAL\n");
"GZ_BAR_KEY=GZ_BAR_VAL\nGZ_BAZ_KEY=GZ_BAZ_VAL\nGZ_FOO_KEY=GZ_FOO_VAL\n");
}

0 comments on commit 55451cc

Please sign in to comment.