Packets: Add StringParser ostream operation
[senf.git] / Utils / Console / Executor.cc
1 // $Id$
2 //
3 // Copyright (C) 2008 
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \file
24     \brief Executor non-inline non-template implementation */
25
26 #include "Executor.hh"
27 //#include "Executor.ih"
28
29 // Custom includes
30 #include <boost/utility.hpp>
31 #include <boost/range/iterator_range.hpp>
32 #include <boost/bind.hpp>
33 #include <boost/format.hpp>
34 #include <boost/preprocessor/stringize.hpp>
35 #include "../../Utils/senfassert.hh"
36 #include "../../Utils/Range.hh"
37 #include "../../Utils/String.hh"
38 #include "../../Utils/range.hh"
39 #include "Server.hh"
40
41 //#include "Executor.mpp"
42 #define prefix_
43 ///////////////////////////////cc.p////////////////////////////////////////
44
45 namespace {
46
47     struct TraversTokens {
48         typedef std::string const & result_type;
49         result_type operator()(senf::console::Token const & token) const {
50             return token.value();
51         }
52     };
53     
54 }
55
56 ///////////////////////////////////////////////////////////////////////////
57 // senf::console::Executor
58
59 prefix_ senf::console::DirectoryNode & senf::console::Executor::cwd()
60     const
61 {
62     SENF_ASSERT( ! cwd_.empty() );
63     while (cwd_.size()>1 && (cwd_.back().expired() || ! cwd_.back().lock()->active()))
64         cwd_.pop_back();
65     return * cwd_.back().lock();
66 }
67
68 prefix_ std::string senf::console::Executor::cwdPath()
69     const
70 {
71     if (skipping())
72         return "";
73     (void) cwd(); // ensure, cwd is live.
74     return "/" + senf::stringJoin(
75         senf::make_transform_range(
76             boost::make_iterator_range(boost::next(cwd_.begin()), cwd_.end()),
77             boost::bind(&DirectoryNode::name, boost::bind(&DirectoryNode::weak_ptr::lock, _1))),
78         "/" );
79 }
80
81 prefix_ void senf::console::Executor::execute(std::ostream & output,
82                                               ParseCommandInfo const & command)
83 {
84     SENF_LOG(( "Executing: " << command ));
85
86     if (! skipping())
87         (void) cwd(); // Prune the cwd path of expired entries
88
89     try {
90         switch(command.builtin()) {
91         case ParseCommandInfo::NoBuiltin : 
92             if (skipping())
93                 return;
94             exec(output, command);
95             break;
96
97         case ParseCommandInfo::BuiltinCD :
98             if (skipping())
99                 break;
100             try {
101                 // The parser ensures, we have exactly one argument
102                 cd(command.commandPath());
103             }
104             catch (IgnoreCommandException &) {
105                 throw SyntaxErrorException(
106                     "'cd' cannot be skipped (don't use 'cd' in conf-files)");
107             }
108             break;
109             
110         case ParseCommandInfo::BuiltinLS :
111             if (skipping())
112                 break;
113             // The parser ensures, we have either one or no argument
114             ls( output, command.commandPath() );
115             break;
116
117         case ParseCommandInfo::BuiltinLR :
118             if (skipping())
119                 break;
120             // The parser ensures, we have either one or no argument
121             lr( output, command.commandPath() );
122             break;
123
124         case ParseCommandInfo::BuiltinPUSHD :
125             // The parser ensures, we have exactly one argument
126             if (skipping())
127                 pushd(command.commandPath());
128             else
129                 exec(output, command);
130             break;
131             
132         case ParseCommandInfo::BuiltinPOPD :
133             // The parser ensures, we have no arguments
134             popd();
135             break;
136             
137         case ParseCommandInfo::BuiltinEXIT :
138             if (skipping())
139                 break;
140             // The parser ensures, we have no arguments
141             exit();
142             break;
143
144         case ParseCommandInfo::BuiltinHELP :
145             if (skipping())
146                 break;
147             // The parser ensures, we have either one or no arguments
148             help( output, command.commandPath() );
149             break;
150
151         }
152     }
153     catch (InvalidPathException & ex) {
154         throw SyntaxErrorException("invalid path") << " '" << ex.path << "'";
155     }
156     catch (InvalidDirectoryException & ex) {
157         throw SyntaxErrorException("invalid directory") << " '" << ex.path << "'";
158     }
159     catch (InvalidCommandException &) {
160         throw SyntaxErrorException("invalid command");
161     }
162     catch (IgnoreCommandException &) {}
163 }
164
165 prefix_ senf::console::GenericNode &
166 senf::console::Executor::getNode(ParseCommandInfo const & command)
167 {
168     return traverseNode(command.commandPath());
169 }
170
171 prefix_ void senf::console::Executor::exec(std::ostream & output,
172                                            ParseCommandInfo const & command)
173 {
174     try {
175         GenericNode & node ( traverseNode(command.commandPath()) );
176         DirectoryNode * dir ( dynamic_cast<DirectoryNode*>(&node) );
177         if ( dir ) {
178             if (! command.tokens().empty())
179                 throw InvalidCommandException();
180             if (command.builtin() == ParseCommandInfo::BuiltinPUSHD)
181                 pushd( command.commandPath() );
182             else if (autocd_) {
183                 cd(command.commandPath());
184             }
185             else
186                 throw InvalidCommandException();
187         } else {
188             boost::any rv;
189             dynamic_cast<CommandNode &>(node)(rv, output, command);
190             if (command.builtin() == ParseCommandInfo::BuiltinPUSHD) {
191                 DirectoryNode::ptr rvdir;
192                 try {
193                     rvdir = boost::any_cast<DirectoryNode::ptr>(rv);
194                 }
195                 catch (boost::bad_any_cast &) {
196                     throw InvalidCommandException();
197                 }
198                 Path newDir (cwd_);
199                 newDir.push_back(rvdir);
200                 dirstack_.push_back(Path());
201                 dirstack_.back().swap(cwd_);
202                 cwd_.swap(newDir);
203             }
204         }
205     }
206     catch (IgnoreCommandException &) {
207         if (command.builtin() == ParseCommandInfo::BuiltinPUSHD) {
208             dirstack_.push_back(Path());
209             dirstack_.back().swap(cwd_);
210         }
211         else
212             throw;
213     }
214 }
215
216
217 prefix_ void senf::console::Executor::cd(ParseCommandInfo::TokensRange dir)
218 {
219     if (dir.size() == 1 && *dir.begin() == WordToken("-")) {
220         cwd_.swap(oldCwd_);
221         (void) cwd(); // Prune any expired items
222     }
223     else {
224         // We need to use a temporary so an error somewhere while traversing the dir does not cause
225         // the current directory to change.
226         Path newDir (cwd_);
227         traverseDirectory(dir, newDir);
228         oldCwd_.swap(cwd_);
229         cwd_.swap(newDir);
230     }
231 }
232
233 prefix_ void senf::console::Executor::ls(std::ostream & output,
234                                          ParseCommandInfo::TokensRange path)
235 {
236 #   define HELP_COLUMN 28
237
238     unsigned width (senf::console::Client::getWidth(output, 80u, 60u)-(HELP_COLUMN+1));
239     Path dir (cwd_);
240     traverseDirectory(path, dir);
241     DirectoryNode & node (*dir.back().lock());
242     DirectoryNode::child_iterator i (node.children().begin());
243     DirectoryNode::child_iterator const i_end (node.children().end());
244     boost::format fmt ("%s%s  %|" BOOST_PP_STRINGIZE(HELP_COLUMN) "t|%s\n");
245     for (; i != i_end; ++i)
246         output << fmt
247             % i->first
248             % ( i->second->isDirectory()
249                 ? "/"
250                 : i->second->isLink()
251                 ? "@"
252                 : "" )
253             % i->second->shorthelp().substr(0,width);
254
255 #   undef HELP_COLUMN
256 }
257
258 #   define HELP_COLUMN 40
259
260 namespace {
261
262     typedef std::map<senf::console::DirectoryNode*,std::string> NodesMap;
263
264     void dolr(std::ostream & output, unsigned width, NodesMap & nodes, std::string const & base, 
265               unsigned level, senf::console::DirectoryNode & node)
266     {
267         boost::format fmt ("%s%s%s  %|" BOOST_PP_STRINGIZE(HELP_COLUMN) "t|%s\n");
268         std::string pad (2*level, ' ');
269         senf::console::DirectoryNode::child_iterator i (node.children().begin());
270         senf::console::DirectoryNode::child_iterator const i_end (node.children().end());
271         for (; i != i_end; ++i) {
272             if (i->second->followLink().isDirectory()) {
273                 senf::console::DirectoryNode & subnode (
274                     static_cast<senf::console::DirectoryNode&>(i->second->followLink()));
275                 NodesMap::iterator j (nodes.find(&subnode));
276                 if (j == nodes.end()) {
277                     output << fmt
278                         % pad % i->first 
279                         % ( i->second->isDirectory() ? "/" : i->second->isLink() ? "@" : "" )
280                         % i->second->shorthelp().substr(0,width);
281                     std::string subbase (base);
282                     if (! subbase.empty())
283                         subbase += "/";
284                     subbase += i->first;
285                     nodes.insert(std::make_pair(&subnode, subbase));
286                     dolr(output, width, nodes, subbase, level+1, subnode);
287                 } else
288                     output << pad << i->first 
289                            << ( i->second->isDirectory() ? "/" : i->second->isLink() ? "@" : "" )
290                            << " -> " << j->second << "\n";
291             } else {
292                 output << fmt
293                     % pad % i->first 
294                     % ( i->second->isDirectory() ? "/" : i->second->isLink() ? "@" : "" )
295                     % i->second->shorthelp().substr(0,width);
296             }
297         }
298     }
299
300 }
301
302 prefix_ void senf::console::Executor::lr(std::ostream & output,
303                                          ParseCommandInfo::TokensRange path)
304 {
305     Path dir (cwd_);
306     traverseDirectory(path, dir);
307     DirectoryNode & node (*dir.back().lock());
308     NodesMap nodes;
309     dolr(output, senf::console::Client::getWidth(output, 80u, 60u)-(HELP_COLUMN+1), 
310          nodes, "", 0, node);
311 }
312
313 #undef HELP_COLUMN
314
315 prefix_ void senf::console::Executor::pushd(ParseCommandInfo::TokensRange dir)
316 {
317     Path newDir (cwd_);
318     if (! skipping()) {
319         try {
320             traverseDirectory(dir, newDir);
321         }
322         catch (IgnoreCommandException &) {
323             newDir.clear();
324         }
325     }
326     dirstack_.push_back(Path());
327     dirstack_.back().swap(cwd_);
328     cwd_.swap(newDir);
329 }
330
331 prefix_ void senf::console::Executor::popd()
332 {
333     if (! dirstack_.empty()) {
334         cwd_.swap(dirstack_.back());
335         dirstack_.pop_back();
336     }
337 }
338
339 prefix_ void senf::console::Executor::exit()
340 {
341     throw ExitException();
342 }
343
344 prefix_ void senf::console::Executor::help(std::ostream & output,
345                                            ParseCommandInfo::TokensRange path)
346 {
347     GenericNode const & node (traverseNode(path));
348     // output << prettyName(typeid(node)) << " at " << node.path() << "\n\n";
349     node.help(output);
350     output << std::flush;
351 }
352
353 prefix_ senf::console::GenericNode &
354 senf::console::Executor::traverseNode(ParseCommandInfo::TokensRange const & path)
355 {
356     if (path.empty())
357         return *cwd_.back().lock();
358     try {
359         Path dir (cwd_);
360         traverseDirectory(boost::make_iterator_range(
361                               path.begin(),
362                               boost::prior(path.end())),
363                           dir);
364         // For auto-cd support we need to check against '.' and '..' here too
365         Token const & tok (*boost::prior(path.end()));
366         if (tok == WordToken("..")) {
367             if (dir.size() > 1)
368                 dir.pop_back();
369             return *dir.back().lock();
370         }
371         DirectoryNode & base (*dir.back().lock());
372         if (tok == WordToken(".") || tok == NoneToken())
373             return base;
374         std::string const & name (complete(base, tok.value()));
375         if (policy_)
376             policy_( base, name );
377         return dir.back().lock()->get(name);
378     }
379     catch (UnknownNodeNameException &) {
380         throw InvalidPathException(
381             senf::stringJoin(
382                 senf::make_transform_range(path, boost::bind(&Token::value, _1)),
383                 "/"));
384     }
385 }
386
387 prefix_ void
388 senf::console::Executor::traverseDirectory(ParseCommandInfo::TokensRange const & path,
389                                            Path & dir)
390 {
391     std::string errorPath;
392     try {
393         ParseCommandInfo::TokensRange::const_iterator i (path.begin());
394         ParseCommandInfo::TokensRange::const_iterator const i_end (path.end());
395         for (; i != i_end; ++i) {
396             if (i != path.begin())
397                 errorPath += "/";
398             errorPath += i->value();
399             if (*i == NoneToken()) {
400                 if (i == path.begin()) {
401                     dir.clear();
402                     dir.push_back(root_);
403                 }
404             }
405             else if (*i == WordToken("..")) {
406                 if (dir.size() > 1)
407                     dir.pop_back();
408             }
409             else if (*i ==  WordToken("."))
410                 ;
411             else {
412                 DirectoryNode & base (*dir.back().lock());
413                 std::string name (complete(base, i->value()));
414                 if (policy_)
415                     policy_( base, name );
416                 dir.push_back(base[name].thisptr());
417             }
418         }
419     }
420     catch (std::bad_cast &) {
421         throw InvalidDirectoryException(errorPath);
422     }
423     catch (UnknownNodeNameException &) {
424         throw InvalidDirectoryException(errorPath);
425     }
426 }
427
428 prefix_ std::string senf::console::Executor::complete(DirectoryNode & dir,
429                                                       std::string const & name)
430 {
431     if (! dir.hasChild(name)) {
432         DirectoryNode::ChildrenRange completions (dir.completions(name));
433         if (has_one_elt(completions))
434             return completions.begin()->first;
435     }
436     return name;
437 }
438
439 prefix_ void senf::console::senf_console_format_value(DirectoryNode::ptr value,
440                                                       std::ostream & os)
441 {
442     if (value)
443         os << "<Directory at '" << value->path() << "'>";
444     else
445         os << "<Null Directory>";
446 }
447
448 ///////////////////////////////cc.e////////////////////////////////////////
449 #undef prefix_
450 //#include "Executor.mpp"
451
452 \f
453 // Local Variables:
454 // mode: c++
455 // fill-column: 100
456 // comment-column: 40
457 // c-file-style: "senf"
458 // indent-tabs-mode: nil
459 // ispell-local-dictionary: "american"
460 // compile-command: "scons -u test"
461 // End: