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"
51 #include <boost/scoped_ptr.hpp>
53 #include "gromacs/legacyheaders/copyrite.h"
54 #include "gromacs/legacyheaders/network.h"
56 #include "gromacs/commandline/cmdlinehelpcontext.h"
57 #include "gromacs/commandline/cmdlinemodule.h"
58 #include "gromacs/commandline/cmdlineparser.h"
59 #include "gromacs/onlinehelp/helpformat.h"
60 #include "gromacs/onlinehelp/helpmanager.h"
61 #include "gromacs/onlinehelp/helptopic.h"
62 #include "gromacs/onlinehelp/helpwritercontext.h"
63 #include "gromacs/options/basicoptions.h"
64 #include "gromacs/options/options.h"
65 #include "gromacs/utility/exceptions.h"
66 #include "gromacs/utility/file.h"
67 #include "gromacs/utility/gmxassert.h"
68 #include "gromacs/utility/init.h"
69 #include "gromacs/utility/programinfo.h"
70 #include "gromacs/utility/stringutil.h"
75 //! Container type for mapping module names to module objects.
76 typedef std::map<std::string, CommandLineModulePointer> CommandLineModuleMap;
78 class CommandLineHelpModule;
83 /********************************************************************
89 static const char name[];
90 static const char title[];
91 static const char *const text[];
94 // The first two are not used.
95 const char RootHelpText::name[] = "";
96 const char RootHelpText::title[] = "";
97 const char *const RootHelpText::text[] = {
98 "Usage: [PROGRAM] <command> [<args>]",
102 * Help topic that forms the root of the help tree for the help subcommand.
104 * \ingroup module_commandline
106 class RootHelpTopic : public CompositeHelpTopic<RootHelpText>
110 * Creates a root help topic.
112 * \param[in] modules List of modules for to use for module listings.
116 explicit RootHelpTopic(const CommandLineModuleMap &modules)
121 virtual void writeHelp(const HelpWriterContext &context) const;
124 void printModuleList(const HelpWriterContext &context) const;
126 const CommandLineModuleMap &modules_;
128 GMX_DISALLOW_COPY_AND_ASSIGN(RootHelpTopic);
131 void RootHelpTopic::writeHelp(const HelpWriterContext &context) const
133 if (context.outputFormat() != eHelpOutputFormat_Console)
135 // TODO: Implement once the situation with Redmine issue #969 is more
137 GMX_THROW(NotImplementedError(
138 "Root help is not implemented for this output format"));
140 writeBasicHelpTopic(context, *this, helpText());
141 // TODO: If/when this list becomes long, it may be better to only print
142 // "common" commands here, and have a separate topic (e.g.,
143 // "help commands") that prints the full list.
144 printModuleList(context);
145 context.writeTextBlock(
146 "For additional help on a command, use '[PROGRAM] help <command>'");
147 writeSubTopicList(context,
148 "\nAdditional help is available on the following topics:");
149 context.writeTextBlock(
150 "To access the help, use '[PROGRAM] help <topic>'.");
153 void RootHelpTopic::printModuleList(const HelpWriterContext &context) const
155 if (context.outputFormat() != eHelpOutputFormat_Console)
157 // TODO: Implement once the situation with Redmine issue #969 is more
159 GMX_THROW(NotImplementedError(
160 "Module list is not implemented for this output format"));
162 int maxNameLength = 0;
163 CommandLineModuleMap::const_iterator module;
164 for (module = modules_.begin(); module != modules_.end(); ++module)
166 int nameLength = static_cast<int>(module->first.length());
167 if (module->second->shortDescription() != NULL
168 && nameLength > maxNameLength)
170 maxNameLength = nameLength;
173 File &file = context.outputFile();
174 TextTableFormatter formatter;
175 formatter.addColumn(NULL, maxNameLength + 1, false);
176 formatter.addColumn(NULL, 72 - maxNameLength, true);
177 formatter.setFirstColumnIndent(4);
179 file.writeLine("Available commands:");
180 for (module = modules_.begin(); module != modules_.end(); ++module)
182 const char *name = module->first.c_str();
183 const char *description = module->second->shortDescription();
184 if (description != NULL)
187 formatter.addColumnLine(0, name);
188 formatter.addColumnLine(1, description);
189 file.writeString(formatter.formatRow());
194 /********************************************************************
195 * ModuleHelpTopic declaration
199 * Help topic wrapper for a command-line module.
201 * This class implements HelpTopicInterface such that it wraps a
202 * CommandLineModuleInterface, allowing subcommand "help <command>"
203 * to produce the help for "<command>".
205 * \ingroup module_commandline
207 class ModuleHelpTopic : public HelpTopicInterface
210 //! Constructs a help topic for a specific module.
211 ModuleHelpTopic(const CommandLineModuleInterface &module,
212 const CommandLineHelpModule &helpModule)
213 : module_(module), helpModule_(helpModule)
217 virtual const char *name() const { return module_.name(); }
218 virtual const char *title() const { return NULL; }
219 virtual bool hasSubTopics() const { return false; }
220 virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
224 virtual void writeHelp(const HelpWriterContext &context) const;
227 const CommandLineModuleInterface &module_;
228 const CommandLineHelpModule &helpModule_;
230 GMX_DISALLOW_COPY_AND_ASSIGN(ModuleHelpTopic);
233 /********************************************************************
234 * HelpExportInterface
238 * Callbacks for exporting help information for command-line modules.
240 * \ingroup module_commandline
242 class HelpExportInterface
245 virtual ~HelpExportInterface() {};
248 * Called once before exporting individual modules.
250 * Can, e.g., open shared output files (e.g., if the output is written
251 * into a single file, or if a separate index is required) and write
254 virtual void startModuleExport() = 0;
256 * Called to export the help for each module.
258 * \param[in] tag Unique tag for the module (gmx-something).
259 * \param[in] module Module for which the help should be exported.
261 virtual void exportModuleHelp(const std::string &tag,
262 const CommandLineModuleInterface &module) = 0;
264 * Called after all modules have been exported.
266 * Can close files opened in startModuleExport(), write footers to them
269 virtual void finishModuleExport() = 0;
272 /********************************************************************
277 * Implements export for man pages.
279 * \ingroup module_commandline
281 class HelpExportMan : public HelpExportInterface
284 virtual void startModuleExport() {}
285 virtual void exportModuleHelp(const std::string &tag,
286 const CommandLineModuleInterface &module);
287 virtual void finishModuleExport() {}
290 void HelpExportMan::exportModuleHelp(const std::string &tag,
291 const CommandLineModuleInterface &module)
293 File file("man1/" + tag + ".1", "w");
295 // TODO: It would be nice to remove the VERSION prefix from the version
296 // string to make it shorter.
297 file.writeLine(formatString(".TH %s 1 \"\" \"%s\" \"GROMACS Manual\"\n",
300 file.writeLine(".SH NAME");
301 file.writeLine(formatString("%s - %s", tag.c_str(),
302 module.shortDescription()));
305 CommandLineHelpContext context(&file, eHelpOutputFormat_Man);
306 std::string displayName(tag);
307 std::replace(displayName.begin(), displayName.end(), '-', ' ');
308 context.setModuleDisplayName(displayName);
309 module.writeHelp(context);
311 file.writeLine(".SH SEE ALSO");
312 file.writeLine(".BR gromacs(7)");
314 file.writeLine("More information about \\fBGROMACS\\fR is available at <\\fIhttp://www.gromacs.org/\\fR>.");
317 /********************************************************************
322 * Implements export for HTML help.
324 * \ingroup module_commandline
326 class HelpExportHtml : public HelpExportInterface
329 virtual void startModuleExport();
330 virtual void exportModuleHelp(const std::string &tag,
331 const CommandLineModuleInterface &module);
332 virtual void finishModuleExport();
335 void writeHtmlHeader(File *file, const std::string &title) const;
336 void writeHtmlFooter(File *file) const;
338 boost::scoped_ptr<File> byNameFile_;
341 void HelpExportHtml::startModuleExport()
343 byNameFile_.reset(new File("byname.html", "w"));
344 writeHtmlHeader(byNameFile_.get(), "GROMACS Programs by Name");
345 byNameFile_->writeLine("<H3>GROMACS Programs Alphabetically</H3>");
348 void HelpExportHtml::exportModuleHelp(const std::string &tag,
349 const CommandLineModuleInterface &module)
351 File file(tag + ".html", "w");
352 writeHtmlHeader(&file, tag);
354 CommandLineHelpContext context(&file, eHelpOutputFormat_Html);
355 std::string displayName(tag);
356 std::replace(displayName.begin(), displayName.end(), '-', ' ');
357 context.setModuleDisplayName(displayName);
358 module.writeHelp(context);
360 writeHtmlFooter(&file);
363 byNameFile_->writeLine(formatString("<a href=\"%s.html\">%s</a> - %s<br>",
364 tag.c_str(), displayName.c_str(),
365 module.shortDescription()));
368 void HelpExportHtml::finishModuleExport()
370 writeHtmlFooter(byNameFile_.get());
371 byNameFile_->close();
374 void HelpExportHtml::writeHtmlHeader(File *file, const std::string &title) const
376 file->writeLine("<HTML>");
377 file->writeLine("<HEAD>");
378 file->writeLine(formatString("<TITLE>%s</TITLE>", title.c_str()));
379 file->writeLine("<LINK rel=stylesheet href=\"../online/style.css\" type=\"text/css\">");
380 file->writeLine("<BODY text=\"#000000\" bgcolor=\"#FFFFFF\" link=\"#0000FF\" vlink=\"#990000\" alink=\"#FF0000\">");
381 file->writeLine("<TABLE WIDTH=\"98%%\" NOBORDER><TR>");
382 file->writeLine("<TD WIDTH=400><TABLE WIDTH=400 NOBORDER>");
383 file->writeLine("<TD WIDTH=116>");
384 file->writeLine("<A HREF=\"http://www.gromacs.org/\">"
385 "<IMG SRC=\"../images/gmxlogo_small.jpg\" BORDER=0>"
387 file->writeLine("</TD>");
388 file->writeLine(formatString("<TD ALIGN=LEFT VALIGN=TOP WIDTH=280>"
389 "<BR><H2>%s</H2>", title.c_str()));
390 file->writeLine("<FONT SIZE=-1><A HREF=\"../online.html\">Main Table of Contents</A></FONT>");
391 file->writeLine("</TD>");
392 file->writeLine("</TABLE></TD>");
393 file->writeLine("<TD WIDTH=\"*\" ALIGN=RIGHT VALIGN=BOTTOM>");
394 file->writeLine(formatString("<P><B>%s</B>", GromacsVersion()));
395 file->writeLine("</TD>");
396 file->writeLine("</TR></TABLE>");
397 file->writeLine("<HR>");
400 void HelpExportHtml::writeHtmlFooter(File *file) const
402 file->writeLine("<P>");
403 file->writeLine("<HR>");
404 file->writeLine("<DIV ALIGN=RIGHT><FONT SIZE=\"-1\">");
405 file->writeLine("<A HREF=\"http://www.gromacs.org\">http://www.gromacs.org</A><BR>");
406 file->writeLine("</FONT></DIV>");
407 file->writeLine("</BODY>");
408 file->writeLine("</HTML>");
413 /********************************************************************
414 * CommandLineHelpModule
419 * Command-line module for producing help.
421 * This module implements the 'help' subcommand that is automatically added by
422 * CommandLineModuleManager.
424 * \ingroup module_commandline
426 class CommandLineHelpModule : public CommandLineModuleInterface
430 * Creates a command-line help module.
432 * \param[in] modules List of modules for to use for module listings.
433 * \throws std::bad_alloc if out of memory.
435 explicit CommandLineHelpModule(const CommandLineModuleMap &modules);
438 * Adds a top-level help topic.
440 * \param[in] topic Help topic to add.
441 * \throws std::bad_alloc if out of memory.
443 void addTopic(HelpTopicPointer topic);
444 //! Sets whether hidden options will be shown in help.
445 void setShowHidden(bool bHidden) { bHidden_ = bHidden; }
447 * Sets an override to show the help for the given module.
449 * If called, the help module directly prints the help for the given
450 * module when called, skipping any other processing.
452 void setModuleOverride(const CommandLineModuleInterface &module)
454 moduleOverride_ = &module;
457 //! Returns the context object for help output.
458 const CommandLineHelpContext &context() const
463 virtual const char *name() const { return "help"; }
464 virtual const char *shortDescription() const
466 return "Print help information";
469 virtual int run(int argc, char *argv[]);
470 virtual void writeHelp(const CommandLineHelpContext &context) const;
473 void exportHelp(HelpExportInterface *exporter) const;
475 boost::scoped_ptr<RootHelpTopic> rootTopic_;
476 const CommandLineModuleMap &modules_;
478 CommandLineHelpContext *context_;
479 const CommandLineModuleInterface *moduleOverride_;
482 GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineHelpModule);
485 CommandLineHelpModule::CommandLineHelpModule(const CommandLineModuleMap &modules)
486 : rootTopic_(new RootHelpTopic(modules)), modules_(modules),
487 context_(NULL), moduleOverride_(NULL), bHidden_(false)
491 void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
493 rootTopic_->addSubTopic(move(topic));
496 int CommandLineHelpModule::run(int argc, char *argv[])
498 const char *const exportFormats[] = { "man", "html", "completion" };
499 std::string exportFormat;
500 Options options(NULL, NULL);
501 options.addOption(StringOption("export").store(&exportFormat)
502 .enumValue(exportFormats));
503 CommandLineParser(&options).parse(&argc, argv);
504 if (!exportFormat.empty())
506 boost::scoped_ptr<HelpExportInterface> exporter;
507 if (exportFormat == "man")
509 exporter.reset(new HelpExportMan);
511 else if (exportFormat == "html")
513 exporter.reset(new HelpExportHtml);
517 GMX_THROW(NotImplementedError("This help format is not implemented"));
519 exportHelp(exporter.get());
523 boost::scoped_ptr<CommandLineHelpContext> context(
524 new CommandLineHelpContext(&File::standardOutput(),
525 eHelpOutputFormat_Console));
526 context->setShowHidden(bHidden_);
527 context_ = context.get();
528 if (moduleOverride_ != NULL)
530 ModuleHelpTopic(*moduleOverride_, *this).writeHelp(context->writerContext());
534 HelpManager helpManager(*rootTopic_, context->writerContext());
537 for (int i = 1; i < argc; ++i)
539 helpManager.enterTopic(argv[i]);
542 catch (const InvalidInputError &ex)
544 fprintf(stderr, "%s\n", ex.what());
547 helpManager.writeCurrentTopic();
551 void CommandLineHelpModule::writeHelp(const CommandLineHelpContext &context) const
553 const HelpWriterContext &writerContext = context.writerContext();
555 if (writerContext.outputFormat() != eHelpOutputFormat_Console)
559 writerContext.writeTextBlock(
560 "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
561 // TODO: More information.
564 void CommandLineHelpModule::exportHelp(HelpExportInterface *exporter) const
566 // TODO: Would be nicer to have the file names supplied by the build system
567 // and/or export a list of files from here.
568 const char *const program =
569 ProgramInfo::getInstance().invariantProgramName().c_str();
571 exporter->startModuleExport();
572 CommandLineModuleMap::const_iterator module;
573 for (module = modules_.begin(); module != modules_.end(); ++module)
575 if (module->second->shortDescription() != NULL)
577 const char *const moduleName = module->first.c_str();
578 std::string tag(formatString("%s-%s", program, moduleName));
579 exporter->exportModuleHelp(tag, *module->second);
582 exporter->finishModuleExport();
588 /********************************************************************
589 * ModuleHelpTopic implementation
592 void ModuleHelpTopic::writeHelp(const HelpWriterContext & /*context*/) const
594 module_.writeHelp(helpModule_.context());
597 /********************************************************************
598 * CMainCommandLineModule
602 * Implements a CommandLineModuleInterface, given a function with C/C++ main()
605 * \ingroup module_commandline
607 class CMainCommandLineModule : public CommandLineModuleInterface
610 //! \copydoc gmx::CommandLineModuleManager::CMainFunction
611 typedef CommandLineModuleManager::CMainFunction CMainFunction;
614 * Creates a wrapper module for the given main function.
616 * \param[in] name Name for the module.
617 * \param[in] shortDescription One-line description for the module.
618 * \param[in] mainFunction Main function to wrap.
620 * Does not throw. This is essential for correct implementation of
621 * CommandLineModuleManager::runAsMainCMain().
623 CMainCommandLineModule(const char *name, const char *shortDescription,
624 CMainFunction mainFunction)
625 : name_(name), shortDescription_(shortDescription),
626 mainFunction_(mainFunction)
630 virtual const char *name() const
634 virtual const char *shortDescription() const
636 return shortDescription_;
639 virtual int run(int argc, char *argv[])
641 return mainFunction_(argc, argv);
643 virtual void writeHelp(const CommandLineHelpContext &context) const
645 const HelpOutputFormat format = context.writerContext().outputFormat();
649 case eHelpOutputFormat_Console:
652 case eHelpOutputFormat_Man:
655 case eHelpOutputFormat_Html:
659 GMX_THROW(NotImplementedError(
660 "Command-line help is not implemented for this output format"));
664 // TODO: The constness should not be cast away.
665 argv[0] = const_cast<char *>(name_);
666 argv[1] = const_cast<char *>("-man");
667 argv[2] = const_cast<char *>(type);
669 GlobalCommandLineHelpContext global(context);
670 mainFunction_(argc, argv);
675 const char *shortDescription_;
676 CMainFunction mainFunction_;
682 /********************************************************************
683 * CommandLineModuleManager::Impl
687 * Private implementation class for CommandLineModuleManager.
689 * \ingroup module_commandline
691 class CommandLineModuleManager::Impl
695 * Initializes the implementation class.
697 * \param programInfo Program information for the running binary.
699 explicit Impl(ProgramInfo *programInfo);
702 * Helper method that adds a given module to the module manager.
704 * \throws std::bad_alloc if out of memory.
706 void addModule(CommandLineModulePointer module);
708 * Creates the help module if it does not yet exist.
710 * \throws std::bad_alloc if out of memory.
712 * This method should be called before accessing \a helpModule_.
714 void ensureHelpModuleExists();
717 * Finds a module that matches a name.
719 * \param[in] name Module name to find.
720 * \returns Iterator to the found module, or
721 * \c modules_.end() if not found.
725 CommandLineModuleMap::const_iterator
726 findModuleByName(const std::string &name) const;
728 * Finds a module that the name of the binary.
730 * \param[in] programInfo Program information object to use.
731 * \throws std::bad_alloc if out of memory.
732 * \returns Iterator to the found module, or
733 * \c modules_.end() if not found.
735 * Checks whether the program is invoked through a symlink whose name
736 * is different from ProgramInfo::realBinaryName(), and if so, checks
737 * if a module name matches the name of the symlink.
739 * Note that the \p programInfo parameter is currently not necessary
740 * (as the program info object is also contained as a member), but it
741 * clarifies the control flow.
743 CommandLineModuleMap::const_iterator
744 findModuleFromBinaryName(const ProgramInfo &programInfo) const;
747 * Processes command-line options for the wrapper binary.
749 * \param[in,out] argc On input, argc passed to run().
750 * On output, argc to be passed to the module.
751 * \param[in,out] argv On input, argv passed to run().
752 * On output, argv to be passed to the module.
753 * \throws InvalidInputError if there are invalid options.
754 * \returns The module that should be run.
756 * Handles command-line options that affect the wrapper binary
757 * (potentially changing the members of \c this in response to the
758 * options). Also finds the module that should be run and the
759 * arguments that should be passed to it.
761 CommandLineModuleInterface *
762 processCommonOptions(int *argc, char ***argv);
765 * Maps module names to module objects.
767 * Owns the contained modules.
769 CommandLineModuleMap modules_;
770 //! Information about the currently running program.
771 ProgramInfo &programInfo_;
773 * Module that implements help for the binary.
775 * The pointed module is owned by the \a modules_ container.
777 CommandLineHelpModule *helpModule_;
778 //! Settings for what to write in the startup header.
779 BinaryInformationSettings binaryInfoSettings_;
780 //! If non-NULL, run this module in single-module mode.
781 CommandLineModuleInterface *singleModule_;
782 //! Whether all stderr output should be suppressed.
784 //! Whether to write the startup information to stdout iso stderr.
788 GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
791 CommandLineModuleManager::Impl::Impl(ProgramInfo *programInfo)
792 : programInfo_(*programInfo), helpModule_(NULL), singleModule_(NULL),
793 bQuiet_(false), bStdOutInfo_(false)
795 binaryInfoSettings_.copyright(true);
798 void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
800 GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
801 "Attempted to register a duplicate module name");
802 ensureHelpModuleExists();
803 HelpTopicPointer helpTopic(new ModuleHelpTopic(*module, *helpModule_));
804 modules_.insert(std::make_pair(std::string(module->name()),
806 helpModule_->addTopic(move(helpTopic));
809 void CommandLineModuleManager::Impl::ensureHelpModuleExists()
811 if (helpModule_ == NULL)
813 helpModule_ = new CommandLineHelpModule(modules_);
814 addModule(CommandLineModulePointer(helpModule_));
818 CommandLineModuleMap::const_iterator
819 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
821 // TODO: Accept unambiguous prefixes?
822 return modules_.find(name);
825 CommandLineModuleMap::const_iterator
826 CommandLineModuleManager::Impl::findModuleFromBinaryName(
827 const ProgramInfo &programInfo) const
829 std::string binaryName = programInfo.invariantProgramName();
830 if (binaryName == programInfo.realBinaryName())
832 return modules_.end();
834 if (binaryName.compare(0, 2, "g_") == 0)
836 binaryName.erase(0, 2);
838 if (binaryName.compare(0, 3, "gmx") == 0)
840 binaryName.erase(0, 3);
842 return findModuleByName(binaryName);
845 CommandLineModuleInterface *
846 CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
848 // Check if we are directly invoking a certain module.
849 CommandLineModuleInterface *module = singleModule_;
852 // Also check for invokation through named symlinks.
853 CommandLineModuleMap::const_iterator moduleIter
854 = findModuleFromBinaryName(programInfo_);
855 if (moduleIter != modules_.end())
857 module = moduleIter->second.get();
862 bool bHidden = false;
863 bool bVersion = false;
864 bool bCopyright = true;
865 // TODO: Print the common options into the help.
866 // TODO: It would be nice to propagate at least the -quiet option to
867 // the modules so that they can also be quiet in response to this.
868 Options options(NULL, NULL);
869 options.addOption(BooleanOption("h").store(&bHelp));
870 options.addOption(BooleanOption("hidden").store(&bHidden));
871 options.addOption(BooleanOption("quiet").store(&bQuiet_));
872 options.addOption(BooleanOption("version").store(&bVersion));
873 options.addOption(BooleanOption("copyright").store(&bCopyright));
877 // If not in single-module mode, process options to the wrapper binary.
878 // TODO: Ideally, this could be done by CommandLineParser.
879 int argcForWrapper = 1;
880 while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
884 if (argcForWrapper > 1)
886 CommandLineParser(&options).parse(&argcForWrapper, *argv);
888 // If no action requested and there is a module specified, process it.
889 if (argcForWrapper < *argc && !bHelp && !bVersion)
891 const char *moduleName = (*argv)[argcForWrapper];
892 CommandLineModuleMap::const_iterator moduleIter
893 = findModuleByName(moduleName);
894 if (moduleIter == modules_.end())
896 std::string message =
897 formatString("'%s' is not a GROMACS command.", moduleName);
898 GMX_THROW(InvalidInputError(message));
900 module = moduleIter->second.get();
901 programInfo_.setDisplayName(
902 programInfo_.realBinaryName() + "-" + moduleIter->first);
903 *argc -= argcForWrapper;
904 *argv += argcForWrapper;
905 // After this point, argc and argv are the same independent of
906 // which path is taken: (*argv)[0] is the module name.
911 // Recognize the common options also after the module name.
912 // TODO: It could be nicer to only recognize -h/-hidden if module is not
914 CommandLineParser(&options).skipUnknown(true).parse(argc, *argv);
917 binaryInfoSettings_.extendedInfo(bVersion);
918 binaryInfoSettings_.copyright(bCopyright);
925 // If no module specified and no other action, show the help.
926 // Also explicitly specifying -h for the wrapper binary goes here.
927 if (module == NULL || bHelp)
929 ensureHelpModuleExists();
932 helpModule_->setModuleOverride(*module);
935 module = helpModule_;
937 if (module == helpModule_)
939 helpModule_->setShowHidden(bHidden);
944 /********************************************************************
945 * CommandLineModuleManager
948 CommandLineModuleManager::CommandLineModuleManager(ProgramInfo *programInfo)
949 : impl_(new Impl(programInfo))
953 CommandLineModuleManager::~CommandLineModuleManager()
957 void CommandLineModuleManager::setQuiet(bool bQuiet)
959 impl_->bQuiet_ = bQuiet;
962 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
964 impl_->addModule(move(module));
967 void CommandLineModuleManager::addModuleCMain(
968 const char *name, const char *shortDescription,
969 CMainFunction mainFunction)
971 CommandLineModulePointer module(
972 new CMainCommandLineModule(name, shortDescription, mainFunction));
973 addModule(move(module));
976 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
978 impl_->ensureHelpModuleExists();
979 impl_->helpModule_->addTopic(move(topic));
982 int CommandLineModuleManager::run(int argc, char *argv[])
984 CommandLineModuleInterface *module;
985 const bool bMaster = (!gmx_mpi_initialized() || gmx_node_rank() == 0);
988 module = impl_->processCommonOptions(&argc, &argv);
990 catch (const std::exception &)
992 if (bMaster && !impl_->bQuiet_)
994 printBinaryInformation(stderr, impl_->programInfo_,
995 impl_->binaryInfoSettings_);
1001 impl_->bQuiet_ = true;
1003 if (!impl_->bQuiet_)
1005 FILE *out = (impl_->bStdOutInfo_ ? stdout : stderr);
1006 printBinaryInformation(out, impl_->programInfo_,
1007 impl_->binaryInfoSettings_);
1014 int rc = module->run(argc, argv);
1015 if (!impl_->bQuiet_)
1023 int CommandLineModuleManager::runAsMainSingleModule(
1024 int argc, char *argv[], CommandLineModuleInterface *module)
1026 ProgramInfo &programInfo = gmx::init(&argc, &argv);
1029 CommandLineModuleManager manager(&programInfo);
1030 manager.impl_->singleModule_ = module;
1031 int rc = manager.run(argc, argv);
1035 catch (const std::exception &ex)
1037 printFatalErrorMessage(stderr, ex);
1038 return processExceptionAtExit(ex);
1043 int CommandLineModuleManager::runAsMainCMain(
1044 int argc, char *argv[], CMainFunction mainFunction)
1046 CMainCommandLineModule module(argv[0], NULL, mainFunction);
1047 return runAsMainSingleModule(argc, argv, &module);