Thrill  0.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
expand_environment_variables.cpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * tlx/string/expand_environment_variables.cpp
3  *
4  * Part of tlx - http://panthema.net/tlx
5  *
6  * Copyright (C) 2018 Timo Bingmann <[email protected]>
7  *
8  * All rights reserved. Published under the Boost Software License, Version 1.0
9  ******************************************************************************/
10 
12 
13 #include <cctype>
14 #include <cstdlib>
15 #include <cstring>
16 
17 namespace tlx {
18 
20  std::string& s = *sp;
21  size_t p = 0;
22  while (p < s.size()) {
23  // find a dollar sing
24  std::string::size_type dp = s.find('$', p);
25  if (dp == std::string::npos)
26  return s;
27 
28  if (dp + 1 < s.size() && s[dp + 1] == '{') {
29  // match "${[^}]*}"
30 
31  // find matching '}'
32  std::string::size_type de = s.find('}', dp + 2);
33  if (de == std::string::npos) {
34  p = dp + 1;
35  continue;
36  }
37 
38  // cut out variable name
39  std::string var = s.substr(dp + 2, de - (dp + 2));
40 
41  const char* v = getenv(var.c_str());
42  if (v == nullptr)
43  v = "";
44  size_t vlen = std::strlen(v);
45 
46  // replace with value
47  s.replace(dp, de - dp + 1, v);
48 
49  p = dp + vlen + 1;
50  }
51  else if (dp + 1 < s.size() &&
52  (std::isalpha(s[dp + 1]) || s[dp + 1] == '_')) {
53 
54  // match "$[a-zA-Z][a-zA-Z0-9]*"
55  std::string::size_type de = dp + 1;
56  while (de < s.size() &&
57  (std::isalnum(s[de]) || s[de] == '_'))
58  ++de;
59 
60  // cut out variable name
61  std::string var = s.substr(dp + 1, de - (dp + 1));
62 
63  const char* v = getenv(var.c_str());
64  if (v == nullptr)
65  v = "";
66  size_t vlen = std::strlen(v);
67 
68  // replace with value
69  s.replace(dp, de - dp, v);
70 
71  p = dp + vlen;
72  }
73  else {
74  p = dp + 1;
75  }
76  }
77  return s;
78 }
79 
81  std::string copy = s;
83  return copy;
84 }
85 
87  std::string copy = s;
89  return copy;
90 }
91 
92 } // namespace tlx
93 
94 /******************************************************************************/
std::string & expand_environment_variables(std::string *sp)
Expand substrings $ABC_123 and ${ABC_123} into the corresponding environment variables.
std::basic_string< char, std::char_traits< char >, Allocator< char > > string
string with Manager tracking
Definition: allocator.hpp:220