libzypp 17.37.17
Env.h
Go to the documentation of this file.
1/*---------------------------------------------------------------------\
2| ____ _ __ __ ___ |
3| |__ / \ / / . \ . \ |
4| / / \ V /| _/ _/ |
5| / /__ | | | | | | |
6| /_____||_| |_| |_| |
7| |
8\---------------------------------------------------------------------*/
11#ifndef ZYPP_BASE_ENV_H
12#define ZYPP_BASE_ENV_H
13
14#include <cstdlib>
15#include <string>
16#include <memory>
17#include <zypp-core/TriBool.h>
19
21namespace zypp
22{
24 namespace env
25 {
32 inline TriBool getenvBool( const C_Str & var_r )
33 {
34 const char * v = ::getenv( var_r.c_str() );
35 if ( v )
36 return str::strToTriBool( v );
37 return indeterminate;
38 }
39
44 struct ScopedSet
45 {
46 ScopedSet( const ScopedSet & ) = delete;
47 ScopedSet & operator=( const ScopedSet & ) = delete;
48
49 ScopedSet( ScopedSet && ) = default;
50 ScopedSet & operator=( ScopedSet && ) = default;
51
52 public:
55 {}
56
58 ScopedSet( std::string var_r, const char * val_r )
59 : _var { std::move(var_r) }
60 {
61 if ( !_var.empty() )
62 {
63 if ( const char * orig = ::getenv( _var.c_str() ) )
64 _val.reset( new std::string( orig ) );
65 setval( val_r );
66 }
67 }
68
71 {
72 if ( !_var.empty() )
73 setval( _val ? _val->c_str() : nullptr );
74 }
75
76 private:
77 void setval( const char * val_r )
78 {
79 if ( val_r )
80 ::setenv( _var.c_str(), val_r, 1 );
81 else
82 ::unsetenv( _var.c_str() );
83 }
84
85 private:
86 std::string _var;
87 std::unique_ptr<std::string> _val;
88 };
89
90 } // namespace env
91
92} // namespace zypp
94#endif // ZYPP_BASE_ENV_H
Convenience char* constructible from std::string and char*, it maps (char*)0 to an empty string.
Definition String.h:92
const char * c_str() const
Definition String.h:117
boost::logic::tribool TriBool
3-state boolean logic (true, false and indeterminate).
Definition String.h:31
Definition Arch.h:364
Namespace intended to collect all environment variables we use.
Definition Env.h:25
TriBool getenvBool(const C_Str &var_r)
If the environment variable var_r is set to a legal true or false string return bool,...
Definition Env.h:32
TriBool strToTriBool(const C_Str &str)
Parse str into a bool if it's a legal true or false string; else indeterminate.
Definition String.cc:96
Easy-to use interface to the ZYPP dependency resolver.
ScopedSet(const ScopedSet &)=delete
ScopedSet & operator=(const ScopedSet &)=delete
void setval(const char *val_r)
Definition Env.h:77
ScopedSet(std::string var_r, const char *val_r)
Set var_r to val_r (unsets var_r if val_r is a nullptr).
Definition Env.h:58
ScopedSet()
Default ctor (NOOP).
Definition Env.h:54
ScopedSet & operator=(ScopedSet &&)=default
ScopedSet(ScopedSet &&)=default
std::string _var
Definition Env.h:86
std::unique_ptr< std::string > _val
Definition Env.h:87
~ScopedSet()
Restore the original setting.
Definition Env.h:70