Imported Upstream version 17.14.0
[platform/upstream/libzypp.git] / zypp / base / Env.h
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/base/Env.h
10  */
11 #ifndef ZYPP_BASE_ENV_H
12 #define ZYPP_BASE_ENV_H
13
14 #include <cstdlib>
15 #include <string>
16 #include <memory>
17
18 ///////////////////////////////////////////////////////////////////
19 namespace zypp
20 {
21   ///////////////////////////////////////////////////////////////////
22   namespace env
23   {
24     ///////////////////////////////////////////////////////////////////
25     /// \class ScopedSet
26     /// \brief Temporarily set/unset an environment variable
27     /// \ingroup g_RAII
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:
37       /** Default ctor (NOOP). */
38       ScopedSet()
39       {}
40
41       /** Set \a var_r to \a val_r (unsets \a var_r if \a val_r is a \c nullptr). */
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
53       /** Restore the original setting. */
54       ~ScopedSet()
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
75   ///////////////////////////////////////////////////////////////////
76 } // namespace zypp
77 ///////////////////////////////////////////////////////////////////
78 #endif // ZYPP_BASE_ENV_H