Red Sessions is a library for accessing arguments and environment variables from anywhere in your program.
It's an implementation of the proposed P1275's Desert Sessions API - See this link for the paper.
Red Session's objective is to provide a set of safe, easy to use utilities to interact with the system's environment and program arguments anywhere, at any time. These utilities should be straight to the point, acting as wrappers around non-portable OS facilities, applying conversions when necessary to keep the API consistent.
What's in the package?
arguments
an immutable wrapper around the oldargv
pointer, behaves like astd::vector<T> const
.environment
an associative container-like class, it let's you get and set environment variables like getting and setting keys in astd::map
, exceptenvironment::operator[]
returns aenvironment::variable
object, see below.environment::variable
is a proxy object for interacting with a single environment variable. It holds the value of a environment variable at the time it's constructed, it's not effected by changes to the system's environment.- To update the value of a
environment::variable
, callenvironment::operator[]
again. environment::variable::split()
function returns a range-like object that can be used to iterate through variables likePATH
that use your system'spath_separator
.
- To update the value of a
- The
join_paths
function allows joining a series ofstd::filesystem::path
into astd::string
using your system'spath_separator
, or a character of your choice.
Both arguments
and environment
are empty classes and can be freely constructed around.
Feel free to open an issue or contact me if you want to share some feedback. 😃
It's as simple as creating an instance and using it like a container.
#include "red/sessions/session.hpp"
red::session::arguments arguments;
for (const auto& a : arguments) {
// reading each arg
}
// ...
auto it = arguments.begin();
*it = "whatever"; // Error, can't modify/add elements to `arguments`
// copy the arguments if you want to modify them
std::vector<std::string> myargs{ arguments.begin(), arguments.end() };
#include "red/sessions/session.hpp"
red::session::environment environment;
// get a value by assinging it to a string
std::string myvar_value = environment["myvar"];
// or keep the environment::variable object it self and do operations on it latter.
auto mypath = environment["PATH"];
std::string_view key = mypath.key(); // "PATH"
std::string_view value = mypath.value(); // value of "PATH" when `mypath` was created
// set
environment["myvar"] = "something clever";
mypath = "a;b;c"; // assigns to PATH
// checking if a variable exists
if (environment.contains("myvar")) {
// do stuff
}
// iterating the environment
for (auto envline : environment)
{
/* 'envline' has the format key=value
PATH=a;b;c
myvar=something clever
HOME=C:\Users\FulanoDeTal
...
*/
}
// erasing a variable
environment.erase("myvar");
// ...