From 55451cc21474ea8f2f862fef80c299b08ddcfc84 Mon Sep 17 00:00:00 2001 From: Michael Carroll Date: Wed, 1 Nov 2023 16:07:56 +0000 Subject: [PATCH] Sort the environment variables Signed-off-by: Michael Carroll --- src/Environment.cc | 10 +++++++++- src/Environment_TEST.cc | 3 ++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/Environment.cc b/src/Environment.cc index 7c2f02f..b18824f 100644 --- a/src/Environment.cc +++ b/src/Environment.cc @@ -17,8 +17,10 @@ #include +#include #include #include +#include extern char ** environ; @@ -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>( + currentEnv.begin(), currentEnv.end()); + std::sort(sorted.begin(), sorted.end()); + for (const auto &[key, value] : sorted) { ret.append(key); ret.append("="); diff --git a/src/Environment_TEST.cc b/src/Environment_TEST.cc index 24da134..6d09923 100644 --- a/src/Environment_TEST.cc +++ b/src/Environment_TEST.cc @@ -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"); }