1 ////////////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright 2006 - 2021, Tomas Babej, Paul Beckingham, Federico Hernandez.
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included
13 // in all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 // SOFTWARE.
22 //
23 // https://www.opensource.org/licenses/mit-license.php
24 //
25 ////////////////////////////////////////////////////////////////////////////////
26 
27 #include <cmake.h>
28 #include <CmdConfig.h>
29 #include <sstream>
30 #include <algorithm>
31 #include <Context.h>
32 #include <JSON.h>
33 #include <shared.h>
34 #include <format.h>
35 
36 ////////////////////////////////////////////////////////////////////////////////
CmdConfig()37 CmdConfig::CmdConfig ()
38 {
39   _keyword               = "config";
40   _usage                 = "task          config [name [value | '']]";
41   _description           = "Change settings in the task configuration";
42   _read_only             = true;
43   _displays_id           = false;
44   _needs_gc              = false;
45   _uses_context          = false;
46   _accepts_filter        = false;
47   _accepts_modifications = false;
48   _accepts_miscellaneous = true;
49   _category              = Command::Category::config;
50 }
51 
52 ////////////////////////////////////////////////////////////////////////////////
setConfigVariable(const std::string & name,const std::string & value,bool confirmation)53 bool CmdConfig::setConfigVariable (
54   const std::string& name,
55   const std::string& value,
56   bool confirmation /* = false */)
57 {
58   // Read .taskrc (or equivalent)
59   std::vector <std::string> contents;
60   File::read (Context::getContext ().config.file (), contents);
61 
62   auto found = false;
63   auto change = false;
64 
65   for (auto& line : contents)
66   {
67     // Get l-trimmed version of the line
68     auto trimmed_line = trim (line, " ");
69 
70     // If there is a comment on the line, it must follow the pattern.
71     auto comment = line.find ('#');
72     auto pos = trimmed_line.find (name + '=');
73 
74     // TODO: Use std::regex here
75     if (pos == 0)
76     {
77       found = true;
78       if (!confirmation ||
79           confirm (format ("Are you sure you want to change the value of '{1}' from '{2}' to '{3}'?", name, Context::getContext ().config.get (name), value)))
80       {
81         auto new_line = line.substr (0, pos + name.length () + 1) + json::encode (value);
82 
83         // Preserve the comment
84         if (comment != std::string::npos)
85           new_line += "  " + line.substr (comment);
86 
87         // Rewrite the line
88         line = new_line;
89         change = true;
90       }
91     }
92   }
93 
94   // Not found, so append instead.
95   if (! found &&
96       (! confirmation ||
97        confirm (format ("Are you sure you want to add '{1}' with a value of '{2}'?", name, value))))
98   {
99     contents.push_back (name + '=' + json::encode (value));
100     change = true;
101   }
102 
103   if (change)
104     File::write (Context::getContext ().config.file (), contents);
105 
106   return change;
107 }
108 
109 ////////////////////////////////////////////////////////////////////////////////
unsetConfigVariable(const std::string & name,bool confirmation)110 int CmdConfig::unsetConfigVariable (const std::string& name, bool confirmation /* = false */)
111 {
112   // Read .taskrc (or equivalent)
113   std::vector <std::string> contents;
114   File::read (Context::getContext ().config.file (), contents);
115 
116   auto found = false;
117   auto change = false;
118 
119   for (auto line = contents.begin (); line != contents.end (); )
120   {
121     auto lineDeleted = false;
122 
123     // Get l-trimmed version of the line
124 
125     // If there is a comment on the line, it must follow the pattern.
126     auto pos = trim (*line, " ").find (name + '=');
127 
128     // TODO: Use std::regex here
129     if (pos == 0)
130     {
131       found = true;
132 
133       // Remove name
134       if (!confirmation ||
135           confirm (format ("Are you sure you want to remove '{1}'?", name)))
136       {
137         // vector::erase method returns a valid iterator to the next object
138         line = contents.erase (line);
139         lineDeleted = true;
140         change = true;
141       }
142     }
143 
144     if (! lineDeleted)
145       line++;
146   }
147 
148   if (change)
149     File::write (Context::getContext ().config.file (), contents);
150 
151   if (change && found)
152     return 0;
153   else if (found)
154     return 1;
155   else
156     return 2;
157 }
158 
159 ////////////////////////////////////////////////////////////////////////////////
execute(std::string & output)160 int CmdConfig::execute (std::string& output)
161 {
162   auto rc = 0;
163   std::stringstream out;
164 
165   // Get the non-attribute, non-fancy command line arguments.
166   std::vector <std::string> words = Context::getContext ().cli2.getWords ();
167 
168   // Support:
169   //   task config name value    # set name to value
170   //   task config name ""       # set name to blank
171   //   task config name          # remove name
172   if (words.size ())
173   {
174     auto confirmation = Context::getContext ().config.getBoolean ("confirmation");
175     auto found = false;
176 
177     auto name = words[0];
178     std::string value = "";
179 
180     // Join the remaining words into config variable's value
181     if (words.size () > 1)
182     {
183       for (unsigned int i = 1; i < words.size (); ++i)
184       {
185         if (i > 1)
186           value += ' ';
187 
188         value += words[i];
189       }
190     }
191 
192     if (name != "")
193     {
194       auto change = false;
195 
196       // task config name value
197       // task config name ""
198       if (words.size () > 1)
199         change = setConfigVariable(name, value, confirmation);
200 
201       // task config name
202       else
203       {
204         rc = unsetConfigVariable(name, confirmation);
205         if (rc == 0)
206         {
207           change = true;
208           found = true;
209         }
210         else if (rc == 1)
211           found = true;
212 
213         if (! found)
214           throw format ("No entry named '{1}' found.", name);
215       }
216 
217       // Show feedback depending on whether .taskrc has been rewritten
218       if (change)
219       {
220         out << format ("Config file {1} modified.", Context::getContext ().config.file ())
221             << '\n';
222       }
223       else
224         out << "No changes made.\n";
225     }
226     else
227       throw std::string ("Specify the name of a config variable to modify.");
228 
229     output = out.str ();
230   }
231   else
232     throw std::string ("Specify the name of a config variable to modify.");
233 
234   return rc;
235 }
236 
237 ////////////////////////////////////////////////////////////////////////////////
CmdCompletionConfig()238 CmdCompletionConfig::CmdCompletionConfig ()
239 {
240   _keyword               = "_config";
241   _usage                 = "task          _config";
242   _description           = "Lists all supported configuration variables, for completion purposes";
243   _read_only             = true;
244   _displays_id           = false;
245   _needs_gc              = false;
246   _uses_context          = false;
247   _accepts_filter        = false;
248   _accepts_modifications = false;
249   _accepts_miscellaneous = false;
250   _category              = Command::Category::internal;
251 }
252 
253 ////////////////////////////////////////////////////////////////////////////////
execute(std::string & output)254 int CmdCompletionConfig::execute (std::string& output)
255 {
256   auto configs = Context::getContext ().config.all ();
257   std::sort (configs.begin (), configs.end ());
258 
259   for (const auto& config : configs)
260     output += config + '\n';
261 
262   return 0;
263 }
264 
265 ////////////////////////////////////////////////////////////////////////////////
266