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"
55 #include "gromacs/legacyheaders/smalloc.h"
57 #include "gromacs/commandline/cmdlinehelpcontext.h"
58 #include "gromacs/commandline/cmdlinemodule.h"
59 #include "gromacs/commandline/cmdlineparser.h"
60 #include "gromacs/fileio/futil.h"
61 #include "gromacs/onlinehelp/helpformat.h"
62 #include "gromacs/onlinehelp/helpmanager.h"
63 #include "gromacs/onlinehelp/helptopic.h"
64 #include "gromacs/onlinehelp/helpwritercontext.h"
65 #include "gromacs/options/basicoptions.h"
66 #include "gromacs/options/options.h"
67 #include "gromacs/utility/exceptions.h"
68 #include "gromacs/utility/file.h"
69 #include "gromacs/utility/gmxassert.h"
70 #include "gromacs/utility/init.h"
71 #include "gromacs/utility/programinfo.h"
72 #include "gromacs/utility/stringutil.h"
73 #include "gromacs/utility/uniqueptr.h"
78 //! Container type for mapping module names to module objects.
79 typedef std::map<std::string, CommandLineModulePointer> CommandLineModuleMap;
80 //! Smart pointer type for managing a CommandLineModuleGroup.
81 typedef gmx_unique_ptr<internal::CommandLineModuleGroupData>::type
82 CommandLineModuleGroupDataPointer;
83 //! Container type for keeping a list of module groups.
84 typedef std::vector<CommandLineModuleGroupDataPointer>
85 CommandLineModuleGroupList;
87 class CommandLineHelpModule;
94 * Internal data for a CommandLineModuleManager module group.
96 * This class contains the state of a module group. CommandLineModuleGroup
97 * provides the public interface to construct/alter the state, and
98 * CommandLineModuleManager and its associated classes use it for help output.
100 * \ingroup module_commandline
102 class CommandLineModuleGroupData
106 * Shorthand for a list of modules contained in the group.
108 * The first element in the contained pair contains the tag
109 * (gmx-something) of the module, and the second element contains the
110 * description. The second element is never NULL.
112 typedef std::vector<std::pair<std::string, const char *> > ModuleList;
115 * Constructs an empty module group.
117 * \param[in] modules List of all modules
118 * (used for checking and default descriptions).
119 * \param[in] title Title of the group.
123 CommandLineModuleGroupData(const CommandLineModuleMap &modules,
125 : allModules_(modules), title_(title)
129 //! Returns the title for the group.
130 const char *title() const { return title_; }
131 //! Returns the list of modules in the group.
132 const ModuleList &modules() const { return modules_; }
135 * Adds a module to the group.
137 * \param[in] name Name of the module.
138 * \param[in] description Description of the module in this group.
139 * \throws std::bad_alloc if out of memory.
141 * If \p description is NULL, the description returned by the module is
144 void addModule(const char *name, const char *description)
146 CommandLineModuleMap::const_iterator moduleIter = allModules_.find(name);
147 GMX_RELEASE_ASSERT(moduleIter != allModules_.end(),
148 "Non-existent module added to a group");
149 if (description == NULL)
151 description = moduleIter->second->shortDescription();
152 GMX_RELEASE_ASSERT(description != NULL,
153 "Module without a description added to a group");
155 const char *const program =
156 ProgramInfo::getInstance().invariantProgramName().c_str();
157 std::string tag(formatString("%s-%s", program, name));
158 modules_.push_back(std::make_pair(tag, description));
162 const CommandLineModuleMap &allModules_;
166 GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineModuleGroupData);
169 } // namespace internal
174 /********************************************************************
180 static const char name[];
181 static const char title[];
182 static const char *const text[];
185 // The first two are not used.
186 const char RootHelpText::name[] = "";
187 const char RootHelpText::title[] = "";
188 const char *const RootHelpText::text[] = {
189 "Usage: [PROGRAM] <command> [<args>]",
193 * Help topic that forms the root of the help tree for the help subcommand.
195 * \ingroup module_commandline
197 class RootHelpTopic : public CompositeHelpTopic<RootHelpText>
201 * Creates a root help topic.
203 * \param[in] modules List of modules for to use for module listings.
207 explicit RootHelpTopic(const CommandLineModuleMap &modules)
212 virtual void writeHelp(const HelpWriterContext &context) const;
215 void printModuleList(const HelpWriterContext &context) const;
217 const CommandLineModuleMap &modules_;
219 GMX_DISALLOW_COPY_AND_ASSIGN(RootHelpTopic);
222 void RootHelpTopic::writeHelp(const HelpWriterContext &context) const
224 if (context.outputFormat() != eHelpOutputFormat_Console)
226 // TODO: Implement once the situation with Redmine issue #969 is more
228 GMX_THROW(NotImplementedError(
229 "Root help is not implemented for this output format"));
231 writeBasicHelpTopic(context, *this, helpText());
232 // TODO: If/when this list becomes long, it may be better to only print
233 // "common" commands here, and have a separate topic (e.g.,
234 // "help commands") that prints the full list.
235 printModuleList(context);
236 context.writeTextBlock(
237 "For additional help on a command, use '[PROGRAM] help <command>'");
238 writeSubTopicList(context,
239 "\nAdditional help is available on the following topics:");
240 context.writeTextBlock(
241 "To access the help, use '[PROGRAM] help <topic>'.");
244 void RootHelpTopic::printModuleList(const HelpWriterContext &context) const
246 if (context.outputFormat() != eHelpOutputFormat_Console)
248 // TODO: Implement once the situation with Redmine issue #969 is more
250 GMX_THROW(NotImplementedError(
251 "Module list is not implemented for this output format"));
253 int maxNameLength = 0;
254 CommandLineModuleMap::const_iterator module;
255 for (module = modules_.begin(); module != modules_.end(); ++module)
257 int nameLength = static_cast<int>(module->first.length());
258 if (module->second->shortDescription() != NULL
259 && nameLength > maxNameLength)
261 maxNameLength = nameLength;
264 File &file = context.outputFile();
265 TextTableFormatter formatter;
266 formatter.addColumn(NULL, maxNameLength + 1, false);
267 formatter.addColumn(NULL, 72 - maxNameLength, true);
268 formatter.setFirstColumnIndent(4);
270 file.writeLine("Available commands:");
271 for (module = modules_.begin(); module != modules_.end(); ++module)
273 const char *name = module->first.c_str();
274 const char *description = module->second->shortDescription();
275 if (description != NULL)
278 formatter.addColumnLine(0, name);
279 formatter.addColumnLine(1, description);
280 file.writeString(formatter.formatRow());
285 /********************************************************************
286 * ModuleHelpTopic declaration
290 * Help topic wrapper for a command-line module.
292 * This class implements HelpTopicInterface such that it wraps a
293 * CommandLineModuleInterface, allowing subcommand "help <command>"
294 * to produce the help for "<command>".
296 * \ingroup module_commandline
298 class ModuleHelpTopic : public HelpTopicInterface
301 //! Constructs a help topic for a specific module.
302 ModuleHelpTopic(const CommandLineModuleInterface &module,
303 const CommandLineHelpModule &helpModule)
304 : module_(module), helpModule_(helpModule)
308 virtual const char *name() const { return module_.name(); }
309 virtual const char *title() const { return NULL; }
310 virtual bool hasSubTopics() const { return false; }
311 virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
315 virtual void writeHelp(const HelpWriterContext &context) const;
318 const CommandLineModuleInterface &module_;
319 const CommandLineHelpModule &helpModule_;
321 GMX_DISALLOW_COPY_AND_ASSIGN(ModuleHelpTopic);
324 /********************************************************************
325 * HelpExportInterface
329 * Callbacks for exporting help information for command-line modules.
331 * \ingroup module_commandline
333 class HelpExportInterface
336 //! Shorthand for a list of modules contained in a group.
337 typedef internal::CommandLineModuleGroupData::ModuleList
340 virtual ~HelpExportInterface() {};
343 * Called once before exporting individual modules.
345 * Can, e.g., open shared output files (e.g., if the output is written
346 * into a single file, or if a separate index is required) and write
349 virtual void startModuleExport() = 0;
351 * Called to export the help for each module.
353 * \param[in] tag Unique tag for the module (gmx-something).
354 * \param[in] module Module for which the help should be exported.
356 virtual void exportModuleHelp(const std::string &tag,
357 const CommandLineModuleInterface &module) = 0;
359 * Called after all modules have been exported.
361 * Can close files opened in startModuleExport(), write footers to them
364 virtual void finishModuleExport() = 0;
367 * Called once before exporting module groups.
369 * Can, e.g., open a single output file for listing all the groups.
371 virtual void startModuleGroupExport() = 0;
373 * Called to export the help for each module group.
375 * \param[in] title Title for the group.
376 * \param[in] modules List of modules in the group.
378 virtual void exportModuleGroup(const char *title,
379 const ModuleGroupContents &modules) = 0;
381 * Called after all module groups have been exported.
383 * Can close files opened in startModuleGroupExport(), write footers to them
386 virtual void finishModuleGroupExport() = 0;
389 /********************************************************************
394 * Implements export for man pages.
396 * \ingroup module_commandline
398 class HelpExportMan : public HelpExportInterface
401 virtual void startModuleExport() {}
402 virtual void exportModuleHelp(const std::string &tag,
403 const CommandLineModuleInterface &module);
404 virtual void finishModuleExport() {}
406 virtual void startModuleGroupExport() {}
407 virtual void exportModuleGroup(const char * /*title*/,
408 const ModuleGroupContents & /*modules*/) {}
409 virtual void finishModuleGroupExport() {}
412 boost::scoped_ptr<File> indexFile_;
415 void HelpExportMan::exportModuleHelp(const std::string &tag,
416 const CommandLineModuleInterface &module)
418 File file("man1/" + tag + ".1", "w");
420 // TODO: It would be nice to remove the VERSION prefix from the version
421 // string to make it shorter.
422 file.writeLine(formatString(".TH %s 1 \"\" \"%s\" \"GROMACS Manual\"\n",
425 file.writeLine(".SH NAME");
426 file.writeLine(formatString("%s - %s", tag.c_str(),
427 module.shortDescription()));
430 CommandLineHelpContext context(&file, eHelpOutputFormat_Man, NULL);
431 std::string displayName(tag);
432 std::replace(displayName.begin(), displayName.end(), '-', ' ');
433 context.setModuleDisplayName(displayName);
434 module.writeHelp(context);
436 file.writeLine(".SH SEE ALSO");
437 file.writeLine(".BR gromacs(7)");
439 file.writeLine("More information about \\fBGROMACS\\fR is available at <\\fIhttp://www.gromacs.org/\\fR>.");
442 /********************************************************************
447 * Implements export for HTML help.
449 * \ingroup module_commandline
451 class HelpExportHtml : public HelpExportInterface
456 virtual void startModuleExport();
457 virtual void exportModuleHelp(const std::string &tag,
458 const CommandLineModuleInterface &module);
459 virtual void finishModuleExport();
461 virtual void startModuleGroupExport();
462 virtual void exportModuleGroup(const char *title,
463 const ModuleGroupContents &modules);
464 virtual void finishModuleGroupExport();
467 void writeHtmlHeader(File *file, const std::string &title) const;
468 void writeHtmlFooter(File *file) const;
470 boost::scoped_ptr<File> indexFile_;
474 HelpExportHtml::HelpExportHtml()
476 char *linksFilename = low_gmxlibfn("links.dat", FALSE, FALSE);
477 if (linksFilename != NULL)
479 scoped_ptr_sfree guard(linksFilename);
480 File linksFile(linksFilename, "r");
482 while (linksFile.readLine(&line))
484 links_.addLink(line, "../online/" + line);
489 void HelpExportHtml::startModuleExport()
491 indexFile_.reset(new File("byname.html", "w"));
492 writeHtmlHeader(indexFile_.get(), "GROMACS Programs by Name");
493 indexFile_->writeLine("<H3>GROMACS Programs Alphabetically</H3>");
496 void HelpExportHtml::exportModuleHelp(const std::string &tag,
497 const CommandLineModuleInterface &module)
499 File file(tag + ".html", "w");
500 writeHtmlHeader(&file, tag);
502 CommandLineHelpContext context(&file, eHelpOutputFormat_Html, &links_);
503 std::string displayName(tag);
504 std::replace(displayName.begin(), displayName.end(), '-', ' ');
505 context.setModuleDisplayName(displayName);
506 module.writeHelp(context);
508 writeHtmlFooter(&file);
511 indexFile_->writeLine(formatString("<a href=\"%s.html\">%s</a> - %s<br>",
512 tag.c_str(), displayName.c_str(),
513 module.shortDescription()));
516 void HelpExportHtml::finishModuleExport()
518 writeHtmlFooter(indexFile_.get());
522 void HelpExportHtml::startModuleGroupExport()
524 indexFile_.reset(new File("bytopic.html", "w"));
525 writeHtmlHeader(indexFile_.get(), "GROMACS Programs by Topic");
526 indexFile_->writeLine("<H3>GROMACS Programs by Topic</H3>");
529 void HelpExportHtml::exportModuleGroup(const char *title,
530 const ModuleGroupContents &modules)
532 indexFile_->writeLine(formatString("<H4>%s</H4>", title));
534 ModuleGroupContents::const_iterator module;
535 for (module = modules.begin(); module != modules.end(); ++module)
537 const std::string &tag(module->first);
538 std::string displayName(tag);
539 std::replace(displayName.begin(), displayName.end(), '-', ' ');
540 indexFile_->writeLine(formatString("<a href=\"%s.html\">%s</a> - %s<br>",
541 tag.c_str(), displayName.c_str(),
546 void HelpExportHtml::finishModuleGroupExport()
548 writeHtmlFooter(indexFile_.get());
552 void HelpExportHtml::writeHtmlHeader(File *file, const std::string &title) const
554 file->writeLine("<HTML>");
555 file->writeLine("<HEAD>");
556 file->writeLine(formatString("<TITLE>%s</TITLE>", title.c_str()));
557 file->writeLine("<LINK rel=stylesheet href=\"../online/style.css\" type=\"text/css\">");
558 file->writeLine("<BODY text=\"#000000\" bgcolor=\"#FFFFFF\" link=\"#0000FF\" vlink=\"#990000\" alink=\"#FF0000\">");
559 file->writeLine("<TABLE WIDTH=\"98%%\" NOBORDER><TR>");
560 file->writeLine("<TD WIDTH=400><TABLE WIDTH=400 NOBORDER>");
561 file->writeLine("<TD WIDTH=116>");
562 file->writeLine("<A HREF=\"http://www.gromacs.org/\">"
563 "<IMG SRC=\"../images/gmxlogo_small.jpg\" BORDER=0>"
565 file->writeLine("</TD>");
566 file->writeLine(formatString("<TD ALIGN=LEFT VALIGN=TOP WIDTH=280>"
567 "<BR><H2>%s</H2>", title.c_str()));
568 file->writeLine("<FONT SIZE=-1><A HREF=\"../online.html\">Main Table of Contents</A></FONT>");
569 file->writeLine("</TD>");
570 file->writeLine("</TABLE></TD>");
571 file->writeLine("<TD WIDTH=\"*\" ALIGN=RIGHT VALIGN=BOTTOM>");
572 file->writeLine(formatString("<P><B>%s</B>", GromacsVersion()));
573 file->writeLine("</TD>");
574 file->writeLine("</TR></TABLE>");
575 file->writeLine("<HR>");
578 void HelpExportHtml::writeHtmlFooter(File *file) const
580 file->writeLine("<P>");
581 file->writeLine("<HR>");
582 file->writeLine("<DIV ALIGN=RIGHT><FONT SIZE=\"-1\">");
583 file->writeLine("<A HREF=\"http://www.gromacs.org\">http://www.gromacs.org</A><BR>");
584 file->writeLine("</FONT></DIV>");
585 file->writeLine("</BODY>");
586 file->writeLine("</HTML>");
591 /********************************************************************
592 * CommandLineHelpModule
597 * Command-line module for producing help.
599 * This module implements the 'help' subcommand that is automatically added by
600 * CommandLineModuleManager.
602 * \ingroup module_commandline
604 class CommandLineHelpModule : public CommandLineModuleInterface
608 * Creates a command-line help module.
610 * \param[in] modules List of modules for to use for module listings.
611 * \param[in] groups List of module groups.
612 * \throws std::bad_alloc if out of memory.
614 CommandLineHelpModule(const CommandLineModuleMap &modules,
615 const CommandLineModuleGroupList &groups);
618 * Adds a top-level help topic.
620 * \param[in] topic Help topic to add.
621 * \throws std::bad_alloc if out of memory.
623 void addTopic(HelpTopicPointer topic);
624 //! Sets whether hidden options will be shown in help.
625 void setShowHidden(bool bHidden) { bHidden_ = bHidden; }
627 * Sets an override to show the help for the given module.
629 * If called, the help module directly prints the help for the given
630 * module when called, skipping any other processing.
632 void setModuleOverride(const CommandLineModuleInterface &module)
634 moduleOverride_ = &module;
637 //! Returns the context object for help output.
638 const CommandLineHelpContext &context() const
643 virtual const char *name() const { return "help"; }
644 virtual const char *shortDescription() const
646 return "Print help information";
649 virtual int run(int argc, char *argv[]);
650 virtual void writeHelp(const CommandLineHelpContext &context) const;
653 void exportHelp(HelpExportInterface *exporter) const;
655 boost::scoped_ptr<RootHelpTopic> rootTopic_;
656 const CommandLineModuleMap &modules_;
657 const CommandLineModuleGroupList &groups_;
659 CommandLineHelpContext *context_;
660 const CommandLineModuleInterface *moduleOverride_;
663 GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineHelpModule);
666 CommandLineHelpModule::CommandLineHelpModule(
667 const CommandLineModuleMap &modules,
668 const CommandLineModuleGroupList &groups)
669 : rootTopic_(new RootHelpTopic(modules)), modules_(modules), groups_(groups),
670 context_(NULL), moduleOverride_(NULL), bHidden_(false)
674 void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
676 rootTopic_->addSubTopic(move(topic));
679 int CommandLineHelpModule::run(int argc, char *argv[])
681 const char *const exportFormats[] = { "man", "html", "completion" };
682 std::string exportFormat;
683 Options options(NULL, NULL);
684 options.addOption(StringOption("export").store(&exportFormat)
685 .enumValue(exportFormats));
686 CommandLineParser(&options).parse(&argc, argv);
687 if (!exportFormat.empty())
689 boost::scoped_ptr<HelpExportInterface> exporter;
690 if (exportFormat == "man")
692 exporter.reset(new HelpExportMan);
694 else if (exportFormat == "html")
696 exporter.reset(new HelpExportHtml);
700 GMX_THROW(NotImplementedError("This help format is not implemented"));
702 exportHelp(exporter.get());
706 boost::scoped_ptr<CommandLineHelpContext> context(
707 new CommandLineHelpContext(&File::standardOutput(),
708 eHelpOutputFormat_Console, NULL));
709 context->setShowHidden(bHidden_);
710 context_ = context.get();
711 if (moduleOverride_ != NULL)
713 ModuleHelpTopic(*moduleOverride_, *this).writeHelp(context->writerContext());
717 HelpManager helpManager(*rootTopic_, context->writerContext());
720 for (int i = 1; i < argc; ++i)
722 helpManager.enterTopic(argv[i]);
725 catch (const InvalidInputError &ex)
727 fprintf(stderr, "%s\n", ex.what());
730 helpManager.writeCurrentTopic();
734 void CommandLineHelpModule::writeHelp(const CommandLineHelpContext &context) const
736 const HelpWriterContext &writerContext = context.writerContext();
738 if (writerContext.outputFormat() != eHelpOutputFormat_Console)
742 writerContext.writeTextBlock(
743 "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
744 // TODO: More information.
747 void CommandLineHelpModule::exportHelp(HelpExportInterface *exporter) const
749 // TODO: Would be nicer to have the file names supplied by the build system
750 // and/or export a list of files from here.
751 const char *const program =
752 ProgramInfo::getInstance().invariantProgramName().c_str();
754 exporter->startModuleExport();
755 CommandLineModuleMap::const_iterator module;
756 for (module = modules_.begin(); module != modules_.end(); ++module)
758 if (module->second->shortDescription() != NULL)
760 const char *const moduleName = module->first.c_str();
761 std::string tag(formatString("%s-%s", program, moduleName));
762 exporter->exportModuleHelp(tag, *module->second);
765 exporter->finishModuleExport();
767 exporter->startModuleGroupExport();
768 CommandLineModuleGroupList::const_iterator group;
769 for (group = groups_.begin(); group != groups_.end(); ++group)
771 exporter->exportModuleGroup((*group)->title(), (*group)->modules());
773 exporter->finishModuleGroupExport();
779 /********************************************************************
780 * ModuleHelpTopic implementation
783 void ModuleHelpTopic::writeHelp(const HelpWriterContext & /*context*/) const
785 module_.writeHelp(helpModule_.context());
788 /********************************************************************
789 * CMainCommandLineModule
793 * Implements a CommandLineModuleInterface, given a function with C/C++ main()
796 * \ingroup module_commandline
798 class CMainCommandLineModule : public CommandLineModuleInterface
801 //! \copydoc gmx::CommandLineModuleManager::CMainFunction
802 typedef CommandLineModuleManager::CMainFunction CMainFunction;
805 * Creates a wrapper module for the given main function.
807 * \param[in] name Name for the module.
808 * \param[in] shortDescription One-line description for the module.
809 * \param[in] mainFunction Main function to wrap.
811 * Does not throw. This is essential for correct implementation of
812 * CommandLineModuleManager::runAsMainCMain().
814 CMainCommandLineModule(const char *name, const char *shortDescription,
815 CMainFunction mainFunction)
816 : name_(name), shortDescription_(shortDescription),
817 mainFunction_(mainFunction)
821 virtual const char *name() const
825 virtual const char *shortDescription() const
827 return shortDescription_;
830 virtual int run(int argc, char *argv[])
832 return mainFunction_(argc, argv);
834 virtual void writeHelp(const CommandLineHelpContext &context) const
836 const HelpOutputFormat format = context.writerContext().outputFormat();
840 case eHelpOutputFormat_Console:
843 case eHelpOutputFormat_Man:
846 case eHelpOutputFormat_Html:
850 GMX_THROW(NotImplementedError(
851 "Command-line help is not implemented for this output format"));
855 // TODO: The constness should not be cast away.
856 argv[0] = const_cast<char *>(name_);
857 argv[1] = const_cast<char *>("-man");
858 argv[2] = const_cast<char *>(type);
860 GlobalCommandLineHelpContext global(context);
861 mainFunction_(argc, argv);
866 const char *shortDescription_;
867 CMainFunction mainFunction_;
873 /********************************************************************
874 * CommandLineModuleManager::Impl
878 * Private implementation class for CommandLineModuleManager.
880 * \ingroup module_commandline
882 class CommandLineModuleManager::Impl
886 * Initializes the implementation class.
888 * \param programInfo Program information for the running binary.
890 explicit Impl(ProgramInfo *programInfo);
893 * Helper method that adds a given module to the module manager.
895 * \throws std::bad_alloc if out of memory.
897 void addModule(CommandLineModulePointer module);
899 * Creates the help module if it does not yet exist.
901 * \throws std::bad_alloc if out of memory.
903 * This method should be called before accessing \a helpModule_.
905 void ensureHelpModuleExists();
908 * Finds a module that matches a name.
910 * \param[in] name Module name to find.
911 * \returns Iterator to the found module, or
912 * \c modules_.end() if not found.
916 CommandLineModuleMap::const_iterator
917 findModuleByName(const std::string &name) const;
919 * Finds a module that the name of the binary.
921 * \param[in] programInfo Program information object to use.
922 * \throws std::bad_alloc if out of memory.
923 * \returns Iterator to the found module, or
924 * \c modules_.end() if not found.
926 * Checks whether the program is invoked through a symlink whose name
927 * is different from ProgramInfo::realBinaryName(), and if so, checks
928 * if a module name matches the name of the symlink.
930 * Note that the \p programInfo parameter is currently not necessary
931 * (as the program info object is also contained as a member), but it
932 * clarifies the control flow.
934 CommandLineModuleMap::const_iterator
935 findModuleFromBinaryName(const ProgramInfo &programInfo) const;
938 * Processes command-line options for the wrapper binary.
940 * \param[in,out] argc On input, argc passed to run().
941 * On output, argc to be passed to the module.
942 * \param[in,out] argv On input, argv passed to run().
943 * On output, argv to be passed to the module.
944 * \throws InvalidInputError if there are invalid options.
945 * \returns The module that should be run.
947 * Handles command-line options that affect the wrapper binary
948 * (potentially changing the members of \c this in response to the
949 * options). Also finds the module that should be run and the
950 * arguments that should be passed to it.
952 CommandLineModuleInterface *
953 processCommonOptions(int *argc, char ***argv);
956 * Maps module names to module objects.
958 * Owns the contained modules.
960 CommandLineModuleMap modules_;
962 * List of groupings for modules for help output.
964 * Owns the contained module group data objects.
965 * CommandLineModuleGroup objects point to the data objects contained
968 CommandLineModuleGroupList moduleGroups_;
969 //! Information about the currently running program.
970 ProgramInfo &programInfo_;
972 * Module that implements help for the binary.
974 * The pointed module is owned by the \a modules_ container.
976 CommandLineHelpModule *helpModule_;
977 //! Settings for what to write in the startup header.
978 BinaryInformationSettings binaryInfoSettings_;
979 //! If non-NULL, run this module in single-module mode.
980 CommandLineModuleInterface *singleModule_;
981 //! Whether all stderr output should be suppressed.
983 //! Whether to write the startup information to stdout iso stderr.
987 GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
990 CommandLineModuleManager::Impl::Impl(ProgramInfo *programInfo)
991 : programInfo_(*programInfo), helpModule_(NULL), singleModule_(NULL),
992 bQuiet_(false), bStdOutInfo_(false)
994 binaryInfoSettings_.copyright(true);
997 void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
999 GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
1000 "Attempted to register a duplicate module name");
1001 ensureHelpModuleExists();
1002 HelpTopicPointer helpTopic(new ModuleHelpTopic(*module, *helpModule_));
1003 modules_.insert(std::make_pair(std::string(module->name()),
1005 helpModule_->addTopic(move(helpTopic));
1008 void CommandLineModuleManager::Impl::ensureHelpModuleExists()
1010 if (helpModule_ == NULL)
1012 helpModule_ = new CommandLineHelpModule(modules_, moduleGroups_);
1013 addModule(CommandLineModulePointer(helpModule_));
1017 CommandLineModuleMap::const_iterator
1018 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
1020 // TODO: Accept unambiguous prefixes?
1021 return modules_.find(name);
1024 CommandLineModuleMap::const_iterator
1025 CommandLineModuleManager::Impl::findModuleFromBinaryName(
1026 const ProgramInfo &programInfo) const
1028 std::string binaryName = programInfo.invariantProgramName();
1029 if (binaryName == programInfo.realBinaryName())
1031 return modules_.end();
1033 if (binaryName.compare(0, 2, "g_") == 0)
1035 binaryName.erase(0, 2);
1037 if (binaryName.compare(0, 3, "gmx") == 0)
1039 binaryName.erase(0, 3);
1041 return findModuleByName(binaryName);
1044 CommandLineModuleInterface *
1045 CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
1047 // Check if we are directly invoking a certain module.
1048 CommandLineModuleInterface *module = singleModule_;
1051 // Also check for invokation through named symlinks.
1052 CommandLineModuleMap::const_iterator moduleIter
1053 = findModuleFromBinaryName(programInfo_);
1054 if (moduleIter != modules_.end())
1056 module = moduleIter->second.get();
1061 bool bHidden = false;
1062 bool bVersion = false;
1063 bool bCopyright = true;
1064 // TODO: Print the common options into the help.
1065 // TODO: It would be nice to propagate at least the -quiet option to
1066 // the modules so that they can also be quiet in response to this.
1067 Options options(NULL, NULL);
1068 options.addOption(BooleanOption("h").store(&bHelp));
1069 options.addOption(BooleanOption("hidden").store(&bHidden));
1070 options.addOption(BooleanOption("quiet").store(&bQuiet_));
1071 options.addOption(BooleanOption("version").store(&bVersion));
1072 options.addOption(BooleanOption("copyright").store(&bCopyright));
1076 // If not in single-module mode, process options to the wrapper binary.
1077 // TODO: Ideally, this could be done by CommandLineParser.
1078 int argcForWrapper = 1;
1079 while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
1083 if (argcForWrapper > 1)
1085 CommandLineParser(&options).parse(&argcForWrapper, *argv);
1087 // If no action requested and there is a module specified, process it.
1088 if (argcForWrapper < *argc && !bHelp && !bVersion)
1090 const char *moduleName = (*argv)[argcForWrapper];
1091 CommandLineModuleMap::const_iterator moduleIter
1092 = findModuleByName(moduleName);
1093 if (moduleIter == modules_.end())
1095 std::string message =
1096 formatString("'%s' is not a GROMACS command.", moduleName);
1097 GMX_THROW(InvalidInputError(message));
1099 module = moduleIter->second.get();
1100 programInfo_.setDisplayName(
1101 programInfo_.realBinaryName() + "-" + moduleIter->first);
1102 *argc -= argcForWrapper;
1103 *argv += argcForWrapper;
1104 // After this point, argc and argv are the same independent of
1105 // which path is taken: (*argv)[0] is the module name.
1110 // Recognize the common options also after the module name.
1111 // TODO: It could be nicer to only recognize -h/-hidden if module is not
1113 CommandLineParser(&options).skipUnknown(true).parse(argc, *argv);
1116 binaryInfoSettings_.extendedInfo(bVersion);
1117 binaryInfoSettings_.copyright(bCopyright);
1121 bStdOutInfo_ = true;
1124 // If no module specified and no other action, show the help.
1125 // Also explicitly specifying -h for the wrapper binary goes here.
1126 if (module == NULL || bHelp)
1128 ensureHelpModuleExists();
1131 helpModule_->setModuleOverride(*module);
1134 module = helpModule_;
1136 if (module == helpModule_)
1138 helpModule_->setShowHidden(bHidden);
1143 /********************************************************************
1144 * CommandLineModuleManager
1147 CommandLineModuleManager::CommandLineModuleManager(ProgramInfo *programInfo)
1148 : impl_(new Impl(programInfo))
1152 CommandLineModuleManager::~CommandLineModuleManager()
1156 void CommandLineModuleManager::setQuiet(bool bQuiet)
1158 impl_->bQuiet_ = bQuiet;
1161 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
1163 impl_->addModule(move(module));
1166 void CommandLineModuleManager::addModuleCMain(
1167 const char *name, const char *shortDescription,
1168 CMainFunction mainFunction)
1170 CommandLineModulePointer module(
1171 new CMainCommandLineModule(name, shortDescription, mainFunction));
1172 addModule(move(module));
1175 CommandLineModuleGroup CommandLineModuleManager::addModuleGroup(
1178 CommandLineModuleGroupDataPointer group(
1179 new internal::CommandLineModuleGroupData(impl_->modules_, title));
1180 impl_->moduleGroups_.push_back(move(group));
1181 return CommandLineModuleGroup(impl_->moduleGroups_.back().get());
1184 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
1186 impl_->ensureHelpModuleExists();
1187 impl_->helpModule_->addTopic(move(topic));
1190 int CommandLineModuleManager::run(int argc, char *argv[])
1192 CommandLineModuleInterface *module;
1193 const bool bMaster = (!gmx_mpi_initialized() || gmx_node_rank() == 0);
1196 module = impl_->processCommonOptions(&argc, &argv);
1198 catch (const std::exception &)
1200 if (bMaster && !impl_->bQuiet_)
1202 printBinaryInformation(stderr, impl_->programInfo_,
1203 impl_->binaryInfoSettings_);
1209 impl_->bQuiet_ = true;
1211 if (!impl_->bQuiet_)
1213 FILE *out = (impl_->bStdOutInfo_ ? stdout : stderr);
1214 printBinaryInformation(out, impl_->programInfo_,
1215 impl_->binaryInfoSettings_);
1222 int rc = module->run(argc, argv);
1223 if (!impl_->bQuiet_)
1231 int CommandLineModuleManager::runAsMainSingleModule(
1232 int argc, char *argv[], CommandLineModuleInterface *module)
1234 ProgramInfo &programInfo = gmx::init(&argc, &argv);
1237 CommandLineModuleManager manager(&programInfo);
1238 manager.impl_->singleModule_ = module;
1239 int rc = manager.run(argc, argv);
1243 catch (const std::exception &ex)
1245 printFatalErrorMessage(stderr, ex);
1246 return processExceptionAtExit(ex);
1251 int CommandLineModuleManager::runAsMainCMain(
1252 int argc, char *argv[], CMainFunction mainFunction)
1254 CMainCommandLineModule module(argv[0], NULL, mainFunction);
1255 return runAsMainSingleModule(argc, argv, &module);
1258 /********************************************************************
1259 * CommandLineModuleGroup
1262 void CommandLineModuleGroup::addModule(const char *name)
1264 impl_->addModule(name, NULL);
1267 void CommandLineModuleGroup::addModuleWithDescription(const char *name,
1268 const char *description)
1270 impl_->addModule(name, description);