libzypp  17.37.5
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>
18 #include <zypp-core/base/String.h>
19 
21 namespace 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
92 } // namespace zypp
94 #endif // ZYPP_BASE_ENV_H
boost::logic::tribool TriBool
3-state boolean logic (true, false and indeterminate).
Definition: String.h:31
Namespace intended to collect all environment variables we use.
Definition: Env.h:24
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
std::unique_ptr< std::string > _val
Definition: Env.h:87
void setval(const char *val_r)
Definition: Env.h:77
const char * c_str() const
Definition: String.h:117
~ScopedSet()
Restore the original setting.
Definition: Env.h:70
Temporarily set/unset an environment variable.
Definition: Env.h:44
TriBool strToTriBool(const C_Str &str)
Parse str into a bool if it&#39;s a legal true or false string; else indeterminate.
Definition: String.cc:96
TriBool getenvBool(const C_Str &var_r)
If the environment variable var_r is set to a legal true or false string return bool, else indeterminate.
Definition: Env.h:32
Convenience char* constructible from std::string and char*, it maps (char*)0 to an empty string...
Definition: String.h:91
ScopedSet()
Default ctor (NOOP).
Definition: Env.h:54
ScopedSet & operator=(const ScopedSet &)=delete
std::string _var
Definition: Env.h:86
Easy-to use interface to the ZYPP dependency resolver.
Definition: Application.cc:19