libzypp 17.31.23
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
19namespace zypp
20{
22 namespace env
23 {
28 struct ScopedSet
29 {
30 ScopedSet( const ScopedSet & ) = delete;
31 ScopedSet & operator=( const ScopedSet & ) = delete;
32
33 ScopedSet( ScopedSet && ) = default;
34 ScopedSet & operator=( ScopedSet && ) = default;
35
36 public:
39 {}
40
42 ScopedSet( std::string var_r, const char * val_r )
43 : _var { std::move(var_r) }
44 {
45 if ( !_var.empty() )
46 {
47 if ( const char * orig = ::getenv( _var.c_str() ) )
48 _val.reset( new std::string( orig ) );
49 setval( val_r );
50 }
51 }
52
55 {
56 if ( !_var.empty() )
57 setval( _val ? _val->c_str() : nullptr );
58 }
59
60 private:
61 void setval( const char * val_r )
62 {
63 if ( val_r )
64 ::setenv( _var.c_str(), val_r, 1 );
65 else
66 ::unsetenv( _var.c_str() );
67 }
68
69 private:
70 std::string _var;
71 std::unique_ptr<std::string> _val;
72 };
73
74 } // namespace env
76} // namespace zypp
78#endif // ZYPP_BASE_ENV_H
Definition: Arch.h:361
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:2
Temporarily set/unset an environment variable.
Definition: Env.h:29
ScopedSet(const ScopedSet &)=delete
ScopedSet & operator=(const ScopedSet &)=delete
void setval(const char *val_r)
Definition: Env.h:61
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:42
ScopedSet()
Default ctor (NOOP).
Definition: Env.h:38
ScopedSet & operator=(ScopedSet &&)=default
ScopedSet(ScopedSet &&)=default
std::string _var
Definition: Env.h:70
std::unique_ptr< std::string > _val
Definition: Env.h:71
~ScopedSet()
Restore the original setting.
Definition: Env.h:54