2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013, by the GROMACS development team, led by
5 * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6 * others, as listed in the AUTHORS file in the top-level source
7 * directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Implements gmx::CommandLineModuleManager.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_commandline
42 #include "cmdlinemodulemanager.h"
50 #include "gromacs/legacyheaders/copyrite.h"
51 #include "gromacs/legacyheaders/network.h"
53 #include "gromacs/commandline/cmdlinemodule.h"
54 #include "gromacs/commandline/cmdlineparser.h"
55 #include "gromacs/onlinehelp/helpformat.h"
56 #include "gromacs/onlinehelp/helpmanager.h"
57 #include "gromacs/onlinehelp/helptopic.h"
58 #include "gromacs/onlinehelp/helpwritercontext.h"
59 #include "gromacs/options/basicoptions.h"
60 #include "gromacs/options/options.h"
61 #include "gromacs/utility/exceptions.h"
62 #include "gromacs/utility/file.h"
63 #include "gromacs/utility/gmxassert.h"
64 #include "gromacs/utility/init.h"
65 #include "gromacs/utility/programinfo.h"
66 #include "gromacs/utility/stringutil.h"
71 //! Container type for mapping module names to module objects.
72 typedef std::map<std::string, CommandLineModulePointer> CommandLineModuleMap;
77 /********************************************************************
83 static const char name[];
84 static const char title[];
85 static const char *const text[];
88 // The first two are not used.
89 const char RootHelpText::name[] = "";
90 const char RootHelpText::title[] = "";
91 const char *const RootHelpText::text[] = {
92 "Usage: [PROGRAM] <command> [<args>]",
96 * Help topic that forms the root of the help tree for the help subcommand.
98 * \ingroup module_commandline
100 class RootHelpTopic : public CompositeHelpTopic<RootHelpText>
104 * Creates a root help topic.
106 * \param[in] modules List of modules for to use for module listings.
110 explicit RootHelpTopic(const CommandLineModuleMap &modules)
115 virtual void writeHelp(const HelpWriterContext &context) const;
118 void printModuleList(const HelpWriterContext &context) const;
120 const CommandLineModuleMap &modules_;
122 GMX_DISALLOW_COPY_AND_ASSIGN(RootHelpTopic);
125 void RootHelpTopic::writeHelp(const HelpWriterContext &context) const
127 if (context.outputFormat() != eHelpOutputFormat_Console)
129 // TODO: Implement once the situation with Redmine issue #969 is more
131 GMX_THROW(NotImplementedError(
132 "Root help is not implemented for this output format"));
134 writeBasicHelpTopic(context, *this, helpText());
135 // TODO: If/when this list becomes long, it may be better to only print
136 // "common" commands here, and have a separate topic (e.g.,
137 // "help commands") that prints the full list.
138 printModuleList(context);
139 context.writeTextBlock(
140 "For additional help on a command, use '[PROGRAM] help <command>'");
141 writeSubTopicList(context,
142 "\nAdditional help is available on the following topics:");
143 context.writeTextBlock(
144 "To access the help, use '[PROGRAM] help <topic>'.");
147 void RootHelpTopic::printModuleList(const HelpWriterContext &context) const
149 if (context.outputFormat() != eHelpOutputFormat_Console)
151 // TODO: Implement once the situation with Redmine issue #969 is more
153 GMX_THROW(NotImplementedError(
154 "Module list is not implemented for this output format"));
156 int maxNameLength = 0;
157 CommandLineModuleMap::const_iterator module;
158 for (module = modules_.begin(); module != modules_.end(); ++module)
160 int nameLength = static_cast<int>(module->first.length());
161 if (module->second->shortDescription() != NULL
162 && nameLength > maxNameLength)
164 maxNameLength = nameLength;
167 File &file = context.outputFile();
168 TextTableFormatter formatter;
169 formatter.addColumn(NULL, maxNameLength + 1, false);
170 formatter.addColumn(NULL, 72 - maxNameLength, true);
171 formatter.setFirstColumnIndent(4);
173 file.writeLine("Available commands:");
174 for (module = modules_.begin(); module != modules_.end(); ++module)
176 const char *name = module->first.c_str();
177 const char *description = module->second->shortDescription();
178 if (description != NULL)
181 formatter.addColumnLine(0, name);
182 formatter.addColumnLine(1, description);
183 file.writeString(formatter.formatRow());
188 /********************************************************************
193 * Help topic wrapper for a command-line module.
195 * This class implements HelpTopicInterface such that it wraps a
196 * CommandLineModuleInterface, allowing subcommand "help <command>"
197 * to produce the help for "<command>".
199 * \ingroup module_commandline
201 class ModuleHelpTopic : public HelpTopicInterface
204 //! Constructs a help topic for a specific module.
205 explicit ModuleHelpTopic(const CommandLineModuleInterface &module)
210 virtual const char *name() const { return module_.name(); }
211 virtual const char *title() const { return NULL; }
212 virtual bool hasSubTopics() const { return false; }
213 virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
217 virtual void writeHelp(const HelpWriterContext &context) const;
220 const CommandLineModuleInterface &module_;
222 GMX_DISALLOW_COPY_AND_ASSIGN(ModuleHelpTopic);
225 void ModuleHelpTopic::writeHelp(const HelpWriterContext &context) const
227 module_.writeHelp(context);
232 /********************************************************************
233 * CommandLineHelpModule
237 * Command-line module for producing help.
239 * This module implements the 'help' subcommand that is automatically added by
240 * CommandLineModuleManager.
242 * \ingroup module_commandline
244 class CommandLineHelpModule : public CommandLineModuleInterface
248 * Creates a command-line help module.
250 * \param[in] modules List of modules for to use for module listings.
251 * \throws std::bad_alloc if out of memory.
253 explicit CommandLineHelpModule(const CommandLineModuleMap &modules);
256 * Adds a top-level help topic.
258 * \param[in] topic Help topic to add.
259 * \throws std::bad_alloc if out of memory.
261 void addTopic(HelpTopicPointer topic);
263 virtual const char *name() const { return "help"; }
264 virtual const char *shortDescription() const
266 return "Print help information";
269 virtual int run(int argc, char *argv[]);
270 virtual void writeHelp(const HelpWriterContext &context) const;
273 CompositeHelpTopicPointer rootTopic_;
275 GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineHelpModule);
278 CommandLineHelpModule::CommandLineHelpModule(const CommandLineModuleMap &modules)
279 : rootTopic_(new RootHelpTopic(modules))
283 void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
285 rootTopic_->addSubTopic(move(topic));
288 int CommandLineHelpModule::run(int argc, char *argv[])
290 HelpWriterContext context(&File::standardOutput(),
291 eHelpOutputFormat_Console);
292 HelpManager helpManager(*rootTopic_, context);
295 for (int i = 1; i < argc; ++i)
297 helpManager.enterTopic(argv[i]);
300 catch (const InvalidInputError &ex)
302 fprintf(stderr, "%s\n", ex.what());
305 helpManager.writeCurrentTopic();
309 void CommandLineHelpModule::writeHelp(const HelpWriterContext &context) const
311 context.writeTextBlock(
312 "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
313 // TODO: More information.
319 /********************************************************************
320 * CMainCommandLineModule
324 * Implements a CommandLineModuleInterface, given a function with C/C++ main()
327 * \ingroup module_commandline
329 class CMainCommandLineModule : public CommandLineModuleInterface
332 //! \copydoc gmx::CommandLineModuleManager::CMainFunction
333 typedef CommandLineModuleManager::CMainFunction CMainFunction;
336 * Creates a wrapper module for the given main function.
338 * \param[in] name Name for the module.
339 * \param[in] shortDescription One-line description for the module.
340 * \param[in] mainFunction Main function to wrap.
342 * Does not throw. This is essential for correct implementation of
343 * CommandLineModuleManager::runAsMainCMain().
345 CMainCommandLineModule(const char *name, const char *shortDescription,
346 CMainFunction mainFunction)
347 : name_(name), shortDescription_(shortDescription),
348 mainFunction_(mainFunction)
352 virtual const char *name() const
356 virtual const char *shortDescription() const
358 return shortDescription_;
361 virtual int run(int argc, char *argv[])
363 return mainFunction_(argc, argv);
365 virtual void writeHelp(const HelpWriterContext &context) const
367 if (context.outputFormat() != eHelpOutputFormat_Console)
369 GMX_THROW(NotImplementedError(
370 "Command-line help is not implemented for this output format"));
373 // TODO: The constness should not be cast away.
374 argv[0] = const_cast<char *>(name_);
375 argv[1] = const_cast<char *>("-h");
376 mainFunction_(2, argv);
381 const char *shortDescription_;
382 CMainFunction mainFunction_;
388 /********************************************************************
389 * CommandLineModuleManager::Impl
393 * Private implementation class for CommandLineModuleManager.
395 * \ingroup module_commandline
397 class CommandLineModuleManager::Impl
401 * Initializes the implementation class.
403 * \param programInfo Program information for the running binary.
405 explicit Impl(ProgramInfo *programInfo);
408 * Finds a module that matches a name.
410 * \param[in] name Module name to find.
411 * \returns Iterator to the found module, or
412 * \c modules_.end() if not found.
416 CommandLineModuleMap::const_iterator
417 findModuleByName(const std::string &name) const;
419 * Finds a module that the name of the binary.
421 * \param[in] programInfo Program information object to use.
422 * \throws std::bad_alloc if out of memory.
423 * \returns Iterator to the found module, or
424 * \c modules_.end() if not found.
426 * Checks whether the program is invoked through a symlink whose name
427 * is different from ProgramInfo::realBinaryName(), and if so, checks
428 * if a module name matches the name of the symlink.
430 * Note that the \p programInfo parameter is currently not necessary
431 * (as the program info object is also contained as a member), but it
432 * clarifies the control flow.
434 CommandLineModuleMap::const_iterator
435 findModuleFromBinaryName(const ProgramInfo &programInfo) const;
438 * Processes command-line options for the wrapper binary.
440 * \param[in,out] argc On input, argc passed to run().
441 * On output, argc to be passed to the module.
442 * \param[in,out] argv On input, argv passed to run().
443 * On output, argv to be passed to the module.
444 * \throws InvalidInputError if there are invalid options.
445 * \returns The module that should be run.
447 * Handles command-line options that affect the wrapper binary
448 * (potentially changing the members of \c this in response to the
449 * options). Also finds the module that should be run and the
450 * arguments that should be passed to it.
452 CommandLineModuleInterface *
453 processCommonOptions(int *argc, char ***argv);
456 * Maps module names to module objects.
458 * Owns the contained modules.
460 CommandLineModuleMap modules_;
461 //! Information about the currently running program.
462 ProgramInfo &programInfo_;
464 * Module that implements help for the binary.
466 * The pointed module is owned by the \a modules_ container.
468 CommandLineHelpModule *helpModule_;
469 //! Settings for what to write in the startup header.
470 BinaryInformationSettings binaryInfoSettings_;
471 //! If non-NULL, run this module in single-module mode.
472 CommandLineModuleInterface *singleModule_;
473 //! Whether all stderr output should be suppressed.
475 //! Whether to write the startup information to stdout iso stderr.
479 GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
482 CommandLineModuleManager::Impl::Impl(ProgramInfo *programInfo)
483 : programInfo_(*programInfo), helpModule_(NULL), singleModule_(NULL),
484 bQuiet_(false), bStdOutInfo_(false)
486 binaryInfoSettings_.copyright(true);
489 CommandLineModuleMap::const_iterator
490 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
492 // TODO: Accept unambiguous prefixes?
493 return modules_.find(name);
496 CommandLineModuleMap::const_iterator
497 CommandLineModuleManager::Impl::findModuleFromBinaryName(
498 const ProgramInfo &programInfo) const
500 std::string binaryName = programInfo.invariantProgramName();
501 if (binaryName == programInfo.realBinaryName())
503 return modules_.end();
505 if (binaryName.compare(0, 2, "g_") == 0)
507 binaryName.erase(0, 2);
509 return findModuleByName(binaryName);
512 CommandLineModuleInterface *
513 CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
515 // Check if we are directly invoking a certain module.
516 CommandLineModuleInterface *module = singleModule_;
519 // Also check for invokation through named symlinks.
520 CommandLineModuleMap::const_iterator moduleIter
521 = findModuleFromBinaryName(programInfo_);
522 if (moduleIter != modules_.end())
524 module = moduleIter->second.get();
529 bool bVersion = false;
530 bool bCopyright = true;
531 // TODO: Print the common options into the help.
532 // TODO: It would be nice to propagate at least the -quiet option to
533 // the modules so that they can also be quiet in response to this.
534 // TODO: Consider handling -h and related options here instead of in the
535 // modules (also -hidden needs to be transfered here to make that work).
536 // That would mean that with -h, all module-specific options would get
537 // ignored. This means that the help output would not depend on the
538 // command line, but would always show the default values (making it
539 // possible to simplify it further), but also that mdrun -h could not be
540 // used for option validation in g_tune_pme.
541 Options options(NULL, NULL);
544 options.addOption(BooleanOption("h").store(&bHelp));
546 options.addOption(BooleanOption("quiet").store(&bQuiet_));
547 options.addOption(BooleanOption("version").store(&bVersion));
548 options.addOption(BooleanOption("copyright").store(&bCopyright));
552 // If not in single-module mode, process options to the wrapper binary.
553 // TODO: Ideally, this could be done by CommandLineParser.
554 int argcForWrapper = 1;
555 while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
559 if (argcForWrapper > 1)
561 CommandLineParser(&options).parse(&argcForWrapper, *argv);
563 // If no action requested and there is a module specified, process it.
564 if (argcForWrapper < *argc && !bHelp && !bVersion)
566 const char *moduleName = (*argv)[argcForWrapper];
567 CommandLineModuleMap::const_iterator moduleIter
568 = findModuleByName(moduleName);
569 if (moduleIter == modules_.end())
571 std::string message =
572 formatString("'%s' is not a GROMACS command.", moduleName);
573 GMX_THROW(InvalidInputError(message));
575 module = moduleIter->second.get();
576 programInfo_.setDisplayName(
577 programInfo_.realBinaryName() + "-" + moduleIter->first);
578 *argc -= argcForWrapper;
579 *argv += argcForWrapper;
580 // After this point, argc and argv are the same independent of
581 // which path is taken: (*argv)[0] is the module name.
586 // In single-module mode, recognize the common options also after the
588 CommandLineParser(&options).skipUnknown(true).parse(argc, *argv);
591 binaryInfoSettings_.extendedInfo(bVersion);
592 binaryInfoSettings_.copyright(bCopyright);
599 // If no module specified and no other action, show the help.
600 // Also explicitly specifying -h for the wrapper binary goes here.
609 /********************************************************************
610 * CommandLineModuleManager
613 CommandLineModuleManager::CommandLineModuleManager(ProgramInfo *programInfo)
614 : impl_(new Impl(programInfo))
618 CommandLineModuleManager::~CommandLineModuleManager()
622 void CommandLineModuleManager::setQuiet(bool bQuiet)
624 impl_->bQuiet_ = bQuiet;
627 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
629 GMX_ASSERT(impl_->modules_.find(module->name()) == impl_->modules_.end(),
630 "Attempted to register a duplicate module name");
631 HelpTopicPointer helpTopic(new ModuleHelpTopic(*module));
632 impl_->modules_.insert(std::make_pair(std::string(module->name()),
634 addHelpTopic(move(helpTopic));
637 void CommandLineModuleManager::addModuleCMain(
638 const char *name, const char *shortDescription,
639 CMainFunction mainFunction)
641 CommandLineModulePointer module(
642 new CMainCommandLineModule(name, shortDescription, mainFunction));
643 addModule(move(module));
646 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
648 if (impl_->helpModule_ == NULL)
650 impl_->helpModule_ = new CommandLineHelpModule(impl_->modules_);
651 addModule(CommandLineModulePointer(impl_->helpModule_));
653 impl_->helpModule_->addTopic(move(topic));
656 int CommandLineModuleManager::run(int argc, char *argv[])
658 CommandLineModuleInterface *module;
659 const bool bMaster = (!gmx_mpi_initialized() || gmx_node_rank() == 0);
662 module = impl_->processCommonOptions(&argc, &argv);
664 catch (const std::exception &)
666 if (bMaster && !impl_->bQuiet_)
668 printBinaryInformation(stderr, impl_->programInfo_,
669 impl_->binaryInfoSettings_);
675 impl_->bQuiet_ = true;
679 FILE *out = (impl_->bStdOutInfo_ ? stdout : stderr);
680 printBinaryInformation(out, impl_->programInfo_,
681 impl_->binaryInfoSettings_);
688 int rc = module->run(argc, argv);
697 int CommandLineModuleManager::runAsMainSingleModule(
698 int argc, char *argv[], CommandLineModuleInterface *module)
700 ProgramInfo &programInfo = gmx::init(&argc, &argv);
703 CommandLineModuleManager manager(&programInfo);
704 manager.impl_->singleModule_ = module;
705 int rc = manager.run(argc, argv);
709 catch (const std::exception &ex)
711 printFatalErrorMessage(stderr, ex);
712 return processExceptionAtExit(ex);
717 int CommandLineModuleManager::runAsMainCMain(
718 int argc, char *argv[], CMainFunction mainFunction)
720 CMainCommandLineModule module(argv[0], NULL, mainFunction);
721 return runAsMainSingleModule(argc, argv, &module);