2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source 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::CommandLineHelpModule.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_commandline
44 #include "cmdlinehelpmodule.h"
49 #include <boost/scoped_ptr.hpp>
51 #include "gromacs/commandline/cmdlinehelpcontext.h"
52 #include "gromacs/commandline/cmdlinehelpwriter.h"
53 #include "gromacs/commandline/cmdlineparser.h"
54 #include "gromacs/onlinehelp/helpformat.h"
55 #include "gromacs/onlinehelp/helpmanager.h"
56 #include "gromacs/onlinehelp/helptopic.h"
57 #include "gromacs/onlinehelp/helpwritercontext.h"
58 #include "gromacs/options/basicoptions.h"
59 #include "gromacs/options/options.h"
60 #include "gromacs/utility/baseversion.h"
61 #include "gromacs/utility/exceptions.h"
62 #include "gromacs/utility/file.h"
63 #include "gromacs/utility/fileredirector.h"
64 #include "gromacs/utility/gmxassert.h"
65 #include "gromacs/utility/programcontext.h"
66 #include "gromacs/utility/stringutil.h"
68 #include "shellcompletions.h"
75 class HelpExportInterface;
79 /********************************************************************
80 * CommandLineHelpModuleImpl declaration
83 class CommandLineHelpModuleImpl
86 CommandLineHelpModuleImpl(const ProgramContextInterface &programContext,
87 const std::string &binaryName,
88 const CommandLineModuleMap &modules,
89 const CommandLineModuleGroupList &groups);
91 void exportHelp(HelpExportInterface *exporter) const;
93 boost::scoped_ptr<RootHelpTopic> rootTopic_;
94 const ProgramContextInterface &programContext_;
95 std::string binaryName_;
96 const CommandLineModuleMap &modules_;
97 const CommandLineModuleGroupList &groups_;
99 CommandLineHelpContext *context_;
100 const CommandLineModuleInterface *moduleOverride_;
103 FileOutputRedirectorInterface *outputRedirector_;
105 GMX_DISALLOW_COPY_AND_ASSIGN(CommandLineHelpModuleImpl);
111 /********************************************************************
117 static const char name[];
118 static const char title[];
119 static const char *const text[];
122 // The first two are not used.
123 const char RootHelpText::name[] = "";
124 const char RootHelpText::title[] = "";
125 const char *const RootHelpText::text[] = { "" };
128 * Help topic that forms the root of the help tree for the help subcommand.
130 * \ingroup module_commandline
132 class RootHelpTopic : public CompositeHelpTopic<RootHelpText>
136 * Creates a root help topic.
140 explicit RootHelpTopic(const CommandLineHelpModuleImpl &helpModule)
141 : helpModule_(helpModule)
145 virtual void writeHelp(const HelpWriterContext &context) const;
148 const CommandLineHelpModuleImpl &helpModule_;
150 GMX_DISALLOW_COPY_AND_ASSIGN(RootHelpTopic);
153 void RootHelpTopic::writeHelp(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 "Root help is not implemented for this output format"));
163 CommandLineCommonOptionsHolder optionsHolder;
164 CommandLineHelpContext cmdlineContext(*helpModule_.context_);
165 cmdlineContext.setModuleDisplayName(helpModule_.binaryName_);
166 optionsHolder.initOptions();
167 // TODO: Add <command> [<args>] into the synopsis.
168 CommandLineHelpWriter(*optionsHolder.options())
169 .writeHelp(cmdlineContext);
171 // TODO: Consider printing a list of "core" commands. Would require someone
172 // to determine such a set...
173 writeSubTopicList(context,
174 "Additional help is available on the following topics:");
175 // TODO: Make these respect the binary name passed in, to make tests work better.
176 context.writeTextBlock("To access the help, use '[PROGRAM] help <topic>'.");
177 context.writeTextBlock("For help on a command, use '[PROGRAM] help <command>'.");
180 /********************************************************************
185 * Help topic for listing the commands.
187 * \ingroup module_commandline
189 class CommandsHelpTopic : public HelpTopicInterface
193 * Creates a command list help topic.
195 * \param[in] helpModule Help module to get module information from.
199 explicit CommandsHelpTopic(const CommandLineHelpModuleImpl &helpModule)
200 : helpModule_(helpModule)
204 virtual const char *name() const { return "commands"; }
205 virtual const char *title() const { return "List of available commands"; }
206 virtual bool hasSubTopics() const { return false; }
207 virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
212 virtual void writeHelp(const HelpWriterContext &context) const;
215 const CommandLineHelpModuleImpl &helpModule_;
217 GMX_DISALLOW_COPY_AND_ASSIGN(CommandsHelpTopic);
220 void CommandsHelpTopic::writeHelp(const HelpWriterContext &context) const
222 if (context.outputFormat() != eHelpOutputFormat_Console)
224 GMX_THROW(NotImplementedError(
225 "Module list is not implemented for this output format"));
227 int maxNameLength = 0;
228 const CommandLineModuleMap &modules = helpModule_.modules_;
229 CommandLineModuleMap::const_iterator module;
230 for (module = modules.begin(); module != modules.end(); ++module)
232 int nameLength = static_cast<int>(module->first.length());
233 if (module->second->shortDescription() != NULL
234 && nameLength > maxNameLength)
236 maxNameLength = nameLength;
239 context.writeTextBlock(
240 "Usage: [PROGRAM] [<options>] <command> [<args>][PAR]"
241 "Available commands:");
242 File &file = context.outputFile();
243 TextTableFormatter formatter;
244 formatter.addColumn(NULL, maxNameLength + 1, false);
245 formatter.addColumn(NULL, 72 - maxNameLength, true);
246 formatter.setFirstColumnIndent(4);
247 for (module = modules.begin(); module != modules.end(); ++module)
249 const char *name = module->first.c_str();
250 const char *description = module->second->shortDescription();
251 if (description != NULL)
254 formatter.addColumnLine(0, name);
255 formatter.addColumnLine(1, description);
256 file.writeString(formatter.formatRow());
259 context.writeTextBlock(
260 "For help on a command, use '[PROGRAM] help <command>'.");
263 /********************************************************************
268 * Help topic wrapper for a command-line module.
270 * This class implements HelpTopicInterface such that it wraps a
271 * CommandLineModuleInterface, allowing subcommand "help <command>"
272 * to produce the help for "<command>".
274 * \ingroup module_commandline
276 class ModuleHelpTopic : public HelpTopicInterface
279 //! Constructs a help topic for a specific module.
280 ModuleHelpTopic(const CommandLineModuleInterface &module,
281 const CommandLineHelpModuleImpl &helpModule)
282 : module_(module), helpModule_(helpModule)
286 virtual const char *name() const { return module_.name(); }
287 virtual const char *title() const { return NULL; }
288 virtual bool hasSubTopics() const { return false; }
289 virtual const HelpTopicInterface *findSubTopic(const char * /*name*/) const
293 virtual void writeHelp(const HelpWriterContext &context) const;
296 const CommandLineModuleInterface &module_;
297 const CommandLineHelpModuleImpl &helpModule_;
299 GMX_DISALLOW_COPY_AND_ASSIGN(ModuleHelpTopic);
302 void ModuleHelpTopic::writeHelp(const HelpWriterContext & /*context*/) const
304 CommandLineHelpContext context(*helpModule_.context_);
305 const char *const program = helpModule_.binaryName_.c_str();
306 context.setModuleDisplayName(formatString("%s %s", program, module_.name()));
307 module_.writeHelp(context);
310 /********************************************************************
311 * HelpExportInterface
315 * Callbacks for exporting help information for command-line modules.
317 * \ingroup module_commandline
319 class HelpExportInterface
322 //! Shorthand for a list of modules contained in a group.
323 typedef CommandLineModuleGroupData::ModuleList ModuleGroupContents;
325 virtual ~HelpExportInterface() {};
328 * Called once before exporting individual modules.
330 * Can, e.g., open shared output files (e.g., if the output is written
331 * into a single file, or if a separate index is required) and write
334 virtual void startModuleExport() = 0;
336 * Called to export the help for each module.
338 * \param[in] module Module for which the help should be exported.
339 * \param[in] tag Unique tag for the module (gmx-something).
340 * \param[in] displayName Display name for the module (gmx something).
342 virtual void exportModuleHelp(
343 const CommandLineModuleInterface &module,
344 const std::string &tag,
345 const std::string &displayName) = 0;
347 * Called after all modules have been exported.
349 * Can close files opened in startModuleExport(), write footers to them
352 virtual void finishModuleExport() = 0;
355 * Called once before exporting module groups.
357 * Can, e.g., open a single output file for listing all the groups.
359 virtual void startModuleGroupExport() = 0;
361 * Called to export the help for each module group.
363 * \param[in] title Title for the group.
364 * \param[in] modules List of modules in the group.
366 virtual void exportModuleGroup(const char *title,
367 const ModuleGroupContents &modules) = 0;
369 * Called after all module groups have been exported.
371 * Can close files opened in startModuleGroupExport(), write footers to them
374 virtual void finishModuleGroupExport() = 0;
378 * Adds hyperlinks to modules within this binary.
380 * \param[in,out] links Links are added here.
381 * \param[in] helpModule Help module to get module information from.
382 * \throws std::bad_alloc if out of memory.
384 * Initializes a HelpLinks object with links to modules defined in
387 * \ingroup module_commandline
389 void initProgramLinks(HelpLinks *links, const CommandLineHelpModuleImpl &helpModule)
391 const char *const program = helpModule.binaryName_.c_str();
392 CommandLineModuleMap::const_iterator module;
393 for (module = helpModule.modules_.begin();
394 module != helpModule.modules_.end();
397 if (module->second->shortDescription() != NULL)
399 std::string linkName("[gmx-" + module->first + "]");
400 const char *name = module->first.c_str();
401 std::string reference(
402 formatString(":doc:`%s %s <%s-%s>`", program, name, program, name));
403 std::string displayName(
404 formatString("[TT]%s %s[tt]", program, name));
405 links->addLink(linkName, reference, displayName);
410 /********************************************************************
411 * HelpExportReStructuredText
415 * Implements export for web pages as reStructuredText.
417 * \ingroup module_commandline
419 class HelpExportReStructuredText : public HelpExportInterface
422 //! Initializes reST exporter.
423 explicit HelpExportReStructuredText(
424 const CommandLineHelpModuleImpl &helpModule);
426 virtual void startModuleExport();
427 virtual void exportModuleHelp(
428 const CommandLineModuleInterface &module,
429 const std::string &tag,
430 const std::string &displayName);
431 virtual void finishModuleExport();
433 virtual void startModuleGroupExport();
434 virtual void exportModuleGroup(const char *title,
435 const ModuleGroupContents &modules);
436 virtual void finishModuleGroupExport();
439 FileOutputRedirectorInterface *outputRedirector_;
441 boost::scoped_ptr<File> indexFile_;
442 boost::scoped_ptr<File> manPagesFile_;
445 HelpExportReStructuredText::HelpExportReStructuredText(
446 const CommandLineHelpModuleImpl &helpModule)
447 : outputRedirector_(helpModule.outputRedirector_),
448 links_(eHelpOutputFormat_Rst)
450 File linksFile("links.dat", "r");
452 while (linksFile.readLine(&line))
454 links_.addLink("[REF]." + line + "[ref]",
455 formatString(":ref:`.%s <%s>`", line.c_str(), line.c_str()),
457 links_.addLink("[REF]" + line + "[ref]", formatString(":ref:`%s`", line.c_str()), line);
460 initProgramLinks(&links_, helpModule);
463 void HelpExportReStructuredText::startModuleExport()
466 new File(outputRedirector_->openFileForWriting("programs/byname.rst")));
467 indexFile_->writeLine("Tools by Name");
468 indexFile_->writeLine("=============");
470 new File(outputRedirector_->openFileForWriting("conf-man.py")));
471 manPagesFile_->writeLine("man_pages = [");
474 void HelpExportReStructuredText::exportModuleHelp(
475 const CommandLineModuleInterface &module,
476 const std::string &tag,
477 const std::string &displayName)
479 // TODO: Ideally, the file would only be touched if it really changes.
480 // This would make Sphinx reruns much faster.
481 File file(outputRedirector_->openFileForWriting("programs/" + tag + ".rst"));
482 file.writeLine(formatString(".. _%s:", displayName.c_str()));
483 if (0 == displayName.compare("gmx mdrun"))
485 // Make an extra link target for the convenience of
486 // MPI-specific documentation
487 file.writeLine(".. _mdrun_mpi:");
490 file.writeLine(displayName);
491 file.writeLine(std::string(displayName.length(), '='));
492 CommandLineHelpContext context(&file, eHelpOutputFormat_Rst, &links_);
493 context.setModuleDisplayName(displayName);
494 module.writeHelp(context);
497 file.writeLine(".. only:: man");
499 file.writeLine(" See also");
500 file.writeLine(" --------");
502 file.writeLine(" :manpage:`gromacs(7)`");
504 file.writeLine(" More information about |Gromacs| is available at <http://www.gromacs.org/>.");
507 indexFile_->writeLine(formatString("* :doc:`%s <%s>` - %s",
508 displayName.c_str(), tag.c_str(),
509 module.shortDescription()));
510 manPagesFile_->writeLine(
511 formatString(" ('programs/%s', '%s', \"%s\", '', 1),",
512 tag.c_str(), tag.c_str(), module.shortDescription()));
515 void HelpExportReStructuredText::finishModuleExport()
519 manPagesFile_->writeLine(" ('man/gromacs.7', 'gromacs', 'molecular dynamics simulation suite', '', 7)");
520 manPagesFile_->writeLine("]");
521 manPagesFile_->close();
522 manPagesFile_.reset();
525 void HelpExportReStructuredText::startModuleGroupExport()
528 new File(outputRedirector_->openFileForWriting("programs/bytopic.rst")));
529 indexFile_->writeLine("Tools by Topic");
530 indexFile_->writeLine("==============");
532 new File(outputRedirector_->openFileForWriting("man/bytopic.rst")));
535 void HelpExportReStructuredText::exportModuleGroup(
537 const ModuleGroupContents &modules)
539 indexFile_->writeLine(title);
540 indexFile_->writeLine(std::string(std::strlen(title), '-'));
541 manPagesFile_->writeLine(title);
542 manPagesFile_->writeLine(std::string(std::strlen(title), '+'));
544 ModuleGroupContents::const_iterator module;
545 for (module = modules.begin(); module != modules.end(); ++module)
547 const std::string &tag(module->first);
548 std::string displayName(tag);
549 // TODO: This does not work if the binary name would contain a dash,
550 // but that is not currently the case.
551 const size_t dashPos = displayName.find('-');
552 GMX_RELEASE_ASSERT(dashPos != std::string::npos,
553 "There should always be at least one dash in the tag");
554 displayName[dashPos] = ' ';
555 indexFile_->writeLine(formatString("| :doc:`%s <%s>` - %s",
556 displayName.c_str(), tag.c_str(),
558 manPagesFile_->writeLine(formatString("| ``%s`` - %s",
562 indexFile_->writeLine();
563 manPagesFile_->writeLine();
566 void HelpExportReStructuredText::finishModuleGroupExport()
570 manPagesFile_->close();
571 manPagesFile_.reset();
574 /********************************************************************
575 * HelpExportCompletion
579 * Implements export for command-line completion.
581 * \ingroup module_commandline
583 class HelpExportCompletion : public HelpExportInterface
586 //! Initializes completion exporter.
587 explicit HelpExportCompletion(const CommandLineHelpModuleImpl &helpModule);
589 virtual void startModuleExport();
590 virtual void exportModuleHelp(
591 const CommandLineModuleInterface &module,
592 const std::string &tag,
593 const std::string &displayName);
594 virtual void finishModuleExport();
596 virtual void startModuleGroupExport() {}
597 virtual void exportModuleGroup(const char * /*title*/,
598 const ModuleGroupContents & /*modules*/) {}
599 virtual void finishModuleGroupExport() {}
602 ShellCompletionWriter bashWriter_;
603 std::vector<std::string> modules_;
606 HelpExportCompletion::HelpExportCompletion(
607 const CommandLineHelpModuleImpl &helpModule)
608 : bashWriter_(helpModule.binaryName_, eShellCompletionFormat_Bash)
612 void HelpExportCompletion::startModuleExport()
614 bashWriter_.startCompletions();
617 void HelpExportCompletion::exportModuleHelp(
618 const CommandLineModuleInterface &module,
619 const std::string & /*tag*/,
620 const std::string & /*displayName*/)
622 modules_.push_back(module.name());
624 CommandLineHelpContext context(&bashWriter_);
625 // We use the display name to pass the name of the module to the
626 // completion writer.
627 context.setModuleDisplayName(module.name());
628 module.writeHelp(context);
632 void HelpExportCompletion::finishModuleExport()
634 CommandLineCommonOptionsHolder optionsHolder;
635 optionsHolder.initOptions();
636 bashWriter_.writeWrapperCompletions(modules_, *optionsHolder.options());
637 bashWriter_.finishCompletions();
642 /********************************************************************
643 * CommandLineHelpModuleImpl implementation
645 CommandLineHelpModuleImpl::CommandLineHelpModuleImpl(
646 const ProgramContextInterface &programContext,
647 const std::string &binaryName,
648 const CommandLineModuleMap &modules,
649 const CommandLineModuleGroupList &groups)
650 : rootTopic_(new RootHelpTopic(*this)), programContext_(programContext),
651 binaryName_(binaryName), modules_(modules), groups_(groups),
652 context_(NULL), moduleOverride_(NULL), bHidden_(false),
653 outputRedirector_(&defaultFileOutputRedirector())
657 void CommandLineHelpModuleImpl::exportHelp(HelpExportInterface *exporter) const
659 // TODO: Would be nicer to have the file names supplied by the build system
660 // and/or export a list of files from here.
661 const char *const program = binaryName_.c_str();
663 exporter->startModuleExport();
664 CommandLineModuleMap::const_iterator module;
665 for (module = modules_.begin(); module != modules_.end(); ++module)
667 if (module->second->shortDescription() != NULL)
669 const char *const moduleName = module->first.c_str();
670 std::string tag(formatString("%s-%s", program, moduleName));
671 std::string displayName(formatString("%s %s", program, moduleName));
672 exporter->exportModuleHelp(*module->second, tag, displayName);
675 exporter->finishModuleExport();
677 exporter->startModuleGroupExport();
678 CommandLineModuleGroupList::const_iterator group;
679 for (group = groups_.begin(); group != groups_.end(); ++group)
681 exporter->exportModuleGroup((*group)->title(), (*group)->modules());
683 exporter->finishModuleGroupExport();
686 /********************************************************************
687 * CommandLineHelpModule
690 CommandLineHelpModule::CommandLineHelpModule(
691 const ProgramContextInterface &programContext,
692 const std::string &binaryName,
693 const CommandLineModuleMap &modules,
694 const CommandLineModuleGroupList &groups)
695 : impl_(new Impl(programContext, binaryName, modules, groups))
699 CommandLineHelpModule::~CommandLineHelpModule()
703 HelpTopicPointer CommandLineHelpModule::createModuleHelpTopic(
704 const CommandLineModuleInterface &module) const
706 return HelpTopicPointer(new ModuleHelpTopic(module, *impl_));
709 void CommandLineHelpModule::addTopic(HelpTopicPointer topic)
711 impl_->rootTopic_->addSubTopic(move(topic));
714 void CommandLineHelpModule::setShowHidden(bool bHidden)
716 impl_->bHidden_ = bHidden;
719 void CommandLineHelpModule::setModuleOverride(
720 const CommandLineModuleInterface &module)
722 impl_->moduleOverride_ = &module;
725 void CommandLineHelpModule::setOutputRedirector(
726 FileOutputRedirectorInterface *output)
728 impl_->outputRedirector_ = output;
731 int CommandLineHelpModule::run(int argc, char *argv[])
733 // Add internal topics lazily here.
734 addTopic(HelpTopicPointer(new CommandsHelpTopic(*impl_)));
736 const char *const exportFormats[] = { "rst", "completion" };
737 std::string exportFormat;
738 Options options(NULL, NULL);
739 options.addOption(StringOption("export").store(&exportFormat)
740 .enumValue(exportFormats));
741 CommandLineParser(&options).parse(&argc, argv);
742 if (!exportFormat.empty())
744 boost::scoped_ptr<HelpExportInterface> exporter;
745 if (exportFormat == "rst")
747 exporter.reset(new HelpExportReStructuredText(*impl_));
749 else if (exportFormat == "completion")
751 exporter.reset(new HelpExportCompletion(*impl_));
755 GMX_THROW(NotImplementedError("This help format is not implemented"));
757 impl_->exportHelp(exporter.get());
761 File &outputFile = impl_->outputRedirector_->standardOutput();
762 HelpLinks links(eHelpOutputFormat_Console);
763 initProgramLinks(&links, *impl_);
764 boost::scoped_ptr<CommandLineHelpContext> context(
765 new CommandLineHelpContext(&outputFile,
766 eHelpOutputFormat_Console, &links));
767 context->setShowHidden(impl_->bHidden_);
768 if (impl_->moduleOverride_ != NULL)
770 context->setModuleDisplayName(impl_->programContext_.displayName());
771 impl_->moduleOverride_->writeHelp(*context);
774 impl_->context_ = context.get();
776 HelpManager helpManager(*impl_->rootTopic_, context->writerContext());
779 for (int i = 1; i < argc; ++i)
781 helpManager.enterTopic(argv[i]);
784 catch (const InvalidInputError &ex)
786 fprintf(stderr, "%s\n", ex.what());
789 helpManager.writeCurrentTopic();
793 void CommandLineHelpModule::writeHelp(const CommandLineHelpContext &context) const
795 const HelpWriterContext &writerContext = context.writerContext();
797 if (writerContext.outputFormat() != eHelpOutputFormat_Console)
801 writerContext.writeTextBlock(
802 "Usage: [PROGRAM] help [<command>|<topic> [<subtopic> [...]]]");
803 // TODO: More information.