NCBI C++ ToolKit
ncbienv.hpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 #ifndef NCBIENV__HPP
2 #define NCBIENV__HPP
3 
4 /* $Id: ncbienv.hpp 101766 2024-02-08 02:34:54Z lavr $
5  * ===========================================================================
6  *
7  * PUBLIC DOMAIN NOTICE
8  * National Center for Biotechnology Information
9  *
10  * This software/database is a "United States Government Work" under the
11  * terms of the United States Copyright Act. It was written as part of
12  * the author's official duties as a United States Government employee and
13  * thus cannot be copyrighted. This software/database is freely available
14  * to the public for use. The National Library of Medicine and the U.S.
15  * Government have not placed any restriction on its use or reproduction.
16  *
17  * Although all reasonable efforts have been taken to ensure the accuracy
18  * and reliability of the software and data, the NLM and the U.S.
19  * Government do not and cannot warrant the performance or results that
20  * may be obtained by using this software or data. The NLM and the U.S.
21  * Government disclaim all warranties, express or implied, including
22  * warranties of performance, merchantability or fitness for any particular
23  * purpose.
24  *
25  * Please cite the author in any work or product based on this material.
26  *
27  * ===========================================================================
28  *
29  * Authors: Denis Vakatov, Eugene Vasilchenko
30  *
31  *
32  */
33 
34 /// @file ncbienv.hpp
35 /// Defines unified interface to application:
36 /// - Environment -- CNcbiEnvironment
37 /// - Command-line args -- CNcbiArguments
38 
39 
40 #include <corelib/ncbimtx.hpp>
41 #include <map>
42 #include <iterator>
43 
44 /// Avoid name clash with the NCBI C Toolkit.
45 #if !defined(NCBI_OS_UNIX) || defined(HAVE_NCBI_C)
46 # if defined(GetProgramName)
47 # undef GetProgramName
48 # endif
49 # define GetProgramName GetProgramName
50 # if defined(SetProgramName)
51 # undef SetProgramName
52 # endif
53 # define SetProgramName SetProgramName
54 #endif
55 
56 
57 /** @addtogroup Environment
58  *
59  * @{
60  */
61 
62 
64 
65 
66 /////////////////////////////////////////////////////////////////////////////
67 ///
68 /// CArgumentsException --
69 ///
70 /// Define exceptions generated by CArgumentsApplication.
71 ///
72 /// CArgumentsException inherits its basic functionality from CCoreException
73 /// and defines additional error codes for applications.
74 
76 {
77 public:
78  /// Error types that arguments processing can generate.
79  enum EErrCode {
80  eNegativeArgc, ///< Negative argc value
81  eNoArgs ///< No arguments
82  };
83 
84  /// Translate from the error code value to its string representation.
85  virtual const char* GetErrCodeString(void) const override;
86 
87  // Standard exception boilerplate code.
89 };
90 
91 
92 
93 /////////////////////////////////////////////////////////////////////////////
94 ///
95 /// CNcbiEnvironment --
96 ///
97 /// Define the application environment.
98 ///
99 /// CNcbiEnvironment provides a data structure for storing, accessing and
100 /// modifying the environment variables accessed by the C library routine
101 /// getenv().
102 ///
103 /// @warning MT-safety: This class is MT-safe for reading the environment;
104 /// but modifying the environment (e.g. calling the Set(name, value) method
105 /// with a "name" that exists, or calling the Unset() method) may invalidate
106 /// the results (string references) previously obtained from Get(), which is
107 /// made to return a string reference for efficiency and performance reasons.
108 
110 {
111 public:
112  /// Constructor.
113  CNcbiEnvironment(void);
114 
115  /// Constructor with the envp parameter.
116  CNcbiEnvironment(const char* const* envp);
117 
118  /// Destructor.
119  virtual ~CNcbiEnvironment(void);
120 
121  /// Reset environment.
122  ///
123  /// Delete all cached entries, load new ones from "envp" (if not NULL).
124  void Reset(const char* const* envp = 0);
125 
126  /// Get environment value by name.
127  ///
128  /// If environmnent value is not cached then call "Load(name)" to load
129  /// the environmnent value. The loaded name/value pair will then be
130  /// cached, too, after the call to "Get()".
131  const string& Get(const string& name, bool* found = NULL) const;
132 
133  /// Find all variable names starting with an optional prefix.
134  void Enumerate(list<string>& names, const string& prefix = kEmptyStr)
135  const;
136 
137  /// Set an environment variable by name
138  ///
139  /// This will throw an exception if setting the variable fails
140  void Set(const string& name, const string& value);
141 
142  /// Delete an environment variable by name
143  /// @param name environment variable name [in]
144  void Unset(const string& name);
145 
146 protected:
147  /// Load value of specified environment variable.
148  virtual string Load(const string& name, bool& found) const;
149 
150 private:
151  /// Cached environment <name,value> pair.
152  struct SEnvValue {
153  SEnvValue(void) : ptr(NULL) {}
154  SEnvValue(const string& v, const TXChar* p) : value(v), ptr(p) {}
155 
156  string value; // cached value
157  // NULL if the corresponding environment variable is unset.
158  // kEmptyXCStr if the value was loaded from the environment.
159  // A string created by strdup() if the value came from Set().
160  const TXChar* ptr;
161  };
163  mutable TCache m_Cache;
165 };
166 
167 
168 
169 /////////////////////////////////////////////////////////////////////////////
170 ///
171 /// CAutoEnvironmentVariable --
172 ///
173 /// Establish an environment setting for a limited time.
174 ///
175 /// CAutoEnvironmentVariable establishes an environment variable setting
176 /// for the lifetime of the instance (which may be associated with a unit
177 /// test case), restoring the previous value (if any) when destroyed.
179 {
180 public:
181  /// Initializes the environment variable passed as an argument to the
182  /// corresponding value ("1" by default)
183  /// @param var_name environment variable name [in]
184  /// @param value value to set the environment variable to [in]
185  CAutoEnvironmentVariable(const CTempString& var_name,
186  const CTempString& value = "1",
188 
189  /// Destructor which restores the modifications made in the environment by
190  /// this class
192 
193 private:
194  /// Affected CNcbiEnvironment instance
196  /// Name of the environment variable manipulated
198  /// Previous value of the environment variable manipulated
199  string m_PrevValue;
200  /// Was the variable originally set at all?
201  bool m_WasSet;
202 };
203 
204 
205 
206 /////////////////////////////////////////////////////////////////////////////
207 ///
208 /// CEnvironmentCleaner --
209 ///
210 /// Remove unwanted settings from the environment, for instance to allow
211 /// test suites to start from suitably clean slates (in which case a global
212 /// static instance may be in order).
214 {
215 public:
216  /// Immediately clean some settings, to be passed in as a NULL-terminated
217  /// sequence of C strings.
218  CEnvironmentCleaner(const char* s = NULL, ...);
219 
220  /// Clean the specified setting.
221  void Clean(const string& name);
222 };
223 
224 
225 
226 /////////////////////////////////////////////////////////////////////////////
227 ///
228 /// CNcbiArguments --
229 ///
230 /// Store application command-line arguments & application name.
231 ///
232 /// CNcbiArgument provides a data structure for storing and accessing the
233 /// command line arguments and application name.
234 
236 {
237 public:
238  /// Constructor.
239  CNcbiArguments(int argc, ///< Standard argument count
240  const char* const* argv, ///< Standard argument vector
241  const string& program_name = kEmptyStr, ///< Program name
242  const string& real_name = kEmptyStr ///< Resolved name
243  );
244 
245  /// Destructor.
246  virtual ~CNcbiArguments(void);
247 
248  /// Copy constructor.
249  CNcbiArguments(const CNcbiArguments& args);
250 
251  /// Assignment operator.
253 
254  /// Reset arguments.
255  ///
256  /// Delete all cached args and program name. Load new ones from "argc",
257  /// "argv", "program_name", and "real_name".
258  void Reset(int argc, ///< Standard argument count
259  const char* const* argv, ///< Standard argument vector
260  const string& program_name = kEmptyStr, ///< Program name
261  const string& real_name = kEmptyStr ///< Resolved name
262  );
263 
264  /// Get size (number) of arguments.
265  SIZE_TYPE Size(void) const { return m_Args.size(); }
266 
267  /// Get the argument specified by "pos".
268  const string& operator[] (SIZE_TYPE pos) const { return m_Args[pos]; }
269 
270  /// Add a new argument.
271  void Add(const string& arg);
272 
273  /// Delete arguments from 1 to n.
274  void Shift(int n=1);
275 
276  /// Get program name.
277  const string& GetProgramName(EFollowLinks follow_links = eIgnoreLinks) const;
278 
279  /// Get program base name.
280  string GetProgramBasename(EFollowLinks follow_links = eIgnoreLinks) const;
281 
282  /// Get program directory name.
283  ///
284  /// Program name includes the last '/'.
285  string GetProgramDirname (EFollowLinks follow_links = eIgnoreLinks) const;
286 
287  /// Set program name. If real_name is supplied, it should be the
288  /// fully resolved path to the executable (whereas program_name
289  /// may legitimately involve symlinks).
290  void SetProgramName(const string& program_name,
291  const string& real_name = kEmptyStr);
292 
293 private:
294  string m_ProgramName; ///< Program name if different from the
295  ///< default m_Args[0]
296  deque<string> m_Args; ///< Queue of arguments
297 
298  mutable string m_ResolvedName;
300 };
301 
302 
304 
305 
306 /* @} */
307 
308 #endif /* NCBIENV__HPP */
CArgumentsException –.
Definition: ncbienv.hpp:76
CAutoEnvironmentVariable –.
Definition: ncbienv.hpp:179
CCoreException –.
Definition: ncbiexpt.hpp:1476
CEnvironmentCleaner –.
Definition: ncbienv.hpp:214
CFastMutex –.
Definition: ncbimtx.hpp:667
CNcbiArguments –.
Definition: ncbienv.hpp:236
CNcbiEnvironment –.
Definition: ncbienv.hpp:110
CTempString implements a light-weight string on top of a storage buffer whose lifetime management is ...
Definition: tempstr.hpp:65
static const struct name_t names[]
static HENV env
Definition: transaction2.c:38
EFollowLinks
Whether to follow symbolic links (also known as shortcuts or aliases)
Definition: ncbimisc.hpp:143
@ eIgnoreLinks
Do not follow symbolic links.
Definition: ncbimisc.hpp:144
#define NULL
Definition: ncbistd.hpp:225
EErrCode
Error types that arguments processing can generate.
Definition: ncbienv.hpp:79
string m_PrevValue
Previous value of the environment variable manipulated.
Definition: ncbienv.hpp:199
deque< string > m_Args
Queue of arguments.
Definition: ncbienv.hpp:296
string m_ProgramName
Program name if different from the default m_Args[0].
Definition: ncbienv.hpp:294
SEnvValue(const string &v, const TXChar *p)
Definition: ncbienv.hpp:154
CFastMutex m_CacheMutex
Definition: ncbienv.hpp:164
SIZE_TYPE Size(void) const
Get size (number) of arguments.
Definition: ncbienv.hpp:265
CFastMutex m_ResolvedNameMutex
Definition: ncbienv.hpp:299
bool m_WasSet
Was the variable originally set at all?
Definition: ncbienv.hpp:201
NCBI_EXCEPTION_DEFAULT(CArgumentsException, CCoreException)
string m_ResolvedName
Definition: ncbienv.hpp:298
map< string, SEnvValue > TCache
Definition: ncbienv.hpp:162
string m_VariableName
Name of the environment variable manipulated.
Definition: ncbienv.hpp:197
AutoPtr< CNcbiEnvironment > m_Env
Affected CNcbiEnvironment instance.
Definition: ncbienv.hpp:195
@ eNegativeArgc
Negative argc value.
Definition: ncbienv.hpp:80
CException & operator=(const CException &)
Private assignment operator to prohibit assignment.
virtual const char * GetErrCodeString(void) const override
Translate from the error code value to its string representation.
Definition: ncbiexpt.cpp:757
#define END_NCBI_SCOPE
End previously defined NCBI scope.
Definition: ncbistl.hpp:103
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
Definition: ncbistl.hpp:100
NCBI_NS_STD::string::size_type SIZE_TYPE
Definition: ncbistr.hpp:132
#define kEmptyStr
Definition: ncbistr.hpp:123
char TXChar
Definition: ncbistr.hpp:172
#define NCBI_XNCBI_EXPORT
Definition: ncbi_export.h:1283
yy_size_t n
const TYPE & Get(const CNamedParameterList *param)
const GenericPointer< typename T::ValueType > T2 value
Definition: pointer.h:1227
#define GetProgramName
Avoid name clash with the NCBI C Toolkit.
Definition: ncbienv.hpp:49
#define SetProgramName
Definition: ncbienv.hpp:53
Multi-threading – mutexes; rw-locks; semaphore.
static const char * prefix[]
Definition: pcregrep.c:405
Cached environment <name,value> pair.
Definition: ncbienv.hpp:152
Modified on Sat Jul 13 13:37:45 2024 by modify_doxy.py rev. 669887