Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
env.cpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
16#include "shambase/print.hpp"
17#include "shambase/string.hpp"
18#include "fmt/core.h"
19#include "shamcmdopt/env.hpp"
20#include <optional>
21#include <utility>
22#include <vector>
23
24std::optional<std::string> shamcmdopt::getenv_str(const char *env_var) {
25 const char *val = std::getenv(env_var);
26 if (val != nullptr) {
27 return std::string(val);
28 }
29 return {};
30}
31
33std::vector<std::pair<std::string, std::string>> env_var_reg = {};
34
35void shamcmdopt::register_env_var_doc(std::string env_var, std::string desc) {
36
37 for (auto &[_env_var, _desc] : env_var_reg) {
38 if (_env_var == env_var) {
40 shambase::format("The env var {} is already registered", env_var));
41 }
42 }
43
44 env_var_reg.push_back({env_var, desc});
45}
46
48
49 if (env_var_reg.empty()) {
50 return;
51 }
52
53 auto stringify = [](std::optional<std::string> val) -> std::string {
54 if (val) {
55 return shambase::format("= {}", *val);
56 }
57 return "";
58 };
59
60 fmt::println("\nEnv variables :");
61 for (const auto &[var, desc] : env_var_reg) {
62 auto val = getenv_str(var.c_str());
63
64 shambase::println(shambase::format(" {:<29} : {}", var, desc));
65
66 if (val) {
67 shambase::println(shambase::format(" = {}", *val));
68 }
69 }
70}
std::vector< std::pair< std::string, std::string > > env_var_reg
List of documented env variables.
Definition env.cpp:33
void println(std::string_view sv)
Prints a string to the console followed by a newline.
Definition print.cpp:37
void throw_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Throw an exception and append the source location to it.
std::optional< std::string > getenv_str(const char *env_var)
Get the content of the environment variable if it exist.
Definition env.cpp:24
void print_help_env_var()
Print the documentation of the environment variables registered with register_env_var_doc()
Definition env.cpp:47
void register_env_var_doc(std::string env_var, std::string desc)
Register the documentation of an environment variable.
Definition env.cpp:35