envsubst.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2015 Tommi Maekitalo
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * As a special exception, you may use this file as part of a free
10  * software library without restriction. Specifically, if other files
11  * instantiate templates or use macros or inline functions from this
12  * file, or you compile this file and link it with other files to
13  * produce an executable, this file does not by itself cause the
14  * resulting executable to be covered by the GNU General Public
15  * License. This exception does not however invalidate any other
16  * reasons why the executable file might be covered by the GNU Library
17  * General Public License.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  */
28 
29 #ifndef ENVSUBST_H
30 #define ENVSUBST_H
31 
32 #include <stdexcept>
33 #include <string>
34 
35 namespace cxxtools
36 {
37  class EnvSubstSyntaxError : public std::runtime_error
38  {
39  public:
40  EnvSubstSyntaxError(const std::string& msg);
41  };
42 
74  class EnvSubst
75  {
76  // make non copyable
77  EnvSubst(const EnvSubst&);
78  EnvSubst& operator=(const EnvSubst&);
79 
80  public:
81  struct Ev
82  {
83  virtual void onChar(char ch) = 0;
84  };
85 
86  private:
87  Ev& _ev;
88  enum {
89  state_0,
90  state_esc,
91  state_varbegin,
92  state_varname,
93  state_bvarname,
94  state_subst0,
95  state_subst,
96  state_nosubst
97  } _state;
98 
99  std::string _varname;
100  EnvSubst* _next;
101 
102  bool isInBracket() const
103  { return _state == state_bvarname
104  || _state == state_subst0
105  || _state == state_subst
106  || _state == state_nosubst; }
107 
108  public:
109  explicit EnvSubst(Ev& ev)
110  : _ev(ev),
111  _state(state_0),
112  _next(0)
113  { }
115  { delete _next; }
116 
117  void parse(char ch);
118  void parseEnd();
119  void reset() { _state = state_0; delete _next; _next = 0; }
120  };
121 
125  std::string envSubst(const std::string& str);
126 }
127 
128 #endif // ENVSUBST_H
129