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