2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014, 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::CommandLineModuleManager.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_commandline
42 #include "cmdlinemodulemanager.h"
49 #include "gromacs/legacyheaders/copyrite.h"
51 #include "gromacs/commandline/cmdlinehelpcontext.h"
52 #include "gromacs/commandline/cmdlinehelpmodule.h"
53 #include "gromacs/commandline/cmdlineinit.h"
54 #include "gromacs/commandline/cmdlinemodule.h"
55 #include "gromacs/commandline/cmdlinemodulemanager-impl.h"
56 #include "gromacs/commandline/cmdlineparser.h"
57 #include "gromacs/commandline/cmdlineprogramcontext.h"
58 #include "gromacs/options/basicoptions.h"
59 #include "gromacs/options/options.h"
60 #include "gromacs/utility/basenetwork.h"
61 #include "gromacs/utility/exceptions.h"
62 #include "gromacs/utility/fatalerror.h"
63 #include "gromacs/utility/gmxassert.h"
64 #include "gromacs/utility/stringutil.h"
66 // For GMX_BINARY_SUFFIX
75 //! \addtogroup module_commandline
78 /********************************************************************
79 * CMainCommandLineModule
83 * Implements a CommandLineModuleInterface, given a function with C/C++ main()
86 class CMainCommandLineModule : public CommandLineModuleInterface
89 //! \copydoc gmx::CommandLineModuleManager::CMainFunction
90 typedef CommandLineModuleManager::CMainFunction CMainFunction;
93 * Creates a wrapper module for the given main function.
95 * \param[in] name Name for the module.
96 * \param[in] shortDescription One-line description for the module.
97 * \param[in] mainFunction Main function to wrap.
99 * Does not throw. This is essential for correct implementation of
100 * CommandLineModuleManager::runAsMainCMain().
102 CMainCommandLineModule(const char *name, const char *shortDescription,
103 CMainFunction mainFunction)
104 : name_(name), shortDescription_(shortDescription),
105 mainFunction_(mainFunction)
109 virtual const char *name() const
113 virtual const char *shortDescription() const
115 return shortDescription_;
118 virtual int run(int argc, char *argv[])
120 return mainFunction_(argc, argv);
122 virtual void writeHelp(const CommandLineHelpContext &context) const
126 // TODO: The constness should not be cast away.
127 argv[0] = const_cast<char *>(name_);
129 GlobalCommandLineHelpContext global(context);
130 mainFunction_(argc, argv);
135 const char *shortDescription_;
136 CMainFunction mainFunction_;
144 /********************************************************************
145 * CommandLineCommonOptionsHolder
148 CommandLineCommonOptionsHolder::CommandLineCommonOptionsHolder()
149 : options_(NULL, NULL), bHelp_(false), bHidden_(false),
150 bQuiet_(false), bVersion_(false), bCopyright_(true), debugLevel_(0)
152 binaryInfoSettings_.copyright(true);
155 CommandLineCommonOptionsHolder::~CommandLineCommonOptionsHolder()
159 void CommandLineCommonOptionsHolder::initOptions()
161 options_.addOption(BooleanOption("h").store(&bHelp_)
162 .description("Print help and quit"));
163 options_.addOption(BooleanOption("hidden").store(&bHidden_)
165 .description("Show hidden options in help"));
166 options_.addOption(BooleanOption("quiet").store(&bQuiet_)
167 .description("Do not print common startup info or quotes"));
168 options_.addOption(BooleanOption("version").store(&bVersion_)
169 .description("Print extended version information and quit"));
170 options_.addOption(BooleanOption("copyright").store(&bCopyright_)
171 .description("Print copyright information on startup"));
172 options_.addOption(IntegerOption("debug").store(&debugLevel_)
173 .hidden().defaultValueIfSet(1)
174 .description("Write file with debug information, "
175 "1: short (default), 2: also x and f"));
178 bool CommandLineCommonOptionsHolder::finishOptions()
181 binaryInfoSettings_.extendedInfo(bVersion_);
182 // The latter condition suppresses the copyright with
184 binaryInfoSettings_.copyright(bCopyright_ && !bQuiet_);
188 /********************************************************************
189 * CommandLineModuleManager::Impl
193 * Private implementation class for CommandLineModuleManager.
195 * \ingroup module_commandline
197 class CommandLineModuleManager::Impl
201 * Initializes the implementation class.
203 * \param[in] binaryName Name of the running binary
204 * (without Gromacs binary suffix or .exe on Windows).
205 * \param programContext Program information for the running binary.
207 Impl(const char *binaryName, CommandLineProgramContext *programContext);
210 * Helper method that adds a given module to the module manager.
212 * \throws std::bad_alloc if out of memory.
214 void addModule(CommandLineModulePointer module);
216 * Creates the help module if it does not yet exist.
218 * \throws std::bad_alloc if out of memory.
220 * This method should be called before accessing \a helpModule_.
222 void ensureHelpModuleExists();
225 * Finds a module that matches a name.
227 * \param[in] name Module name to find.
228 * \returns Iterator to the found module, or
229 * \c modules_.end() if not found.
233 CommandLineModuleMap::const_iterator
234 findModuleByName(const std::string &name) const;
236 * Finds a module that the name of the binary.
238 * \param[in] invokedName Name by which the program was invoked.
239 * \throws std::bad_alloc if out of memory.
240 * \returns Iterator to the found module, or
241 * \c modules_.end() if not found.
243 * Checks whether the program is invoked through a symlink whose name
244 * is different from \a binaryName_, and if so, checks
245 * if a module name matches the name of the symlink.
247 * Note that the \p invokedName parameter is currently not necessary
248 * (as the program context object is also available and provides this
249 * value), but it clarifies the control flow.
251 CommandLineModuleMap::const_iterator
252 findModuleFromBinaryName(const char *invokedName) const;
255 * Processes command-line options for the wrapper binary.
257 * \param[in,out] optionsHolder Common options.
258 * \param[in,out] argc On input, argc passed to run().
259 * On output, argc to be passed to the module.
260 * \param[in,out] argv On input, argv passed to run().
261 * On output, argv to be passed to the module.
262 * \throws InvalidInputError if there are invalid options.
263 * \returns The module that should be run.
265 * Handles command-line options that affect the wrapper binary
266 * (potentially changing the members of \c this in response to the
267 * options). Also finds the module that should be run and the
268 * arguments that should be passed to it.
270 CommandLineModuleInterface *
271 processCommonOptions(CommandLineCommonOptionsHolder *optionsHolder,
272 int *argc, char ***argv);
275 * Maps module names to module objects.
277 * Owns the contained modules.
279 CommandLineModuleMap modules_;
281 * List of groupings for modules for help output.
283 * Owns the contained module group data objects.
284 * CommandLineModuleGroup objects point to the data objects contained
287 CommandLineModuleGroupList moduleGroups_;
288 //! Information about the currently running program.
289 CommandLineProgramContext &programContext_;
290 //! Name of the binary.
291 std::string binaryName_;
293 * Module that implements help for the binary.
295 * The pointed module is owned by the \a modules_ container.
297 CommandLineHelpModule *helpModule_;
298 //! If non-NULL, run this module in single-module mode.
299 CommandLineModuleInterface *singleModule_;
300 //! Stores the value set with setQuiet().
304 GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
307 CommandLineModuleManager::Impl::Impl(const char *binaryName,
308 CommandLineProgramContext *programContext)
309 : programContext_(*programContext),
310 binaryName_(binaryName != NULL ? binaryName : ""),
311 helpModule_(NULL), singleModule_(NULL),
314 GMX_RELEASE_ASSERT(binaryName_.find('-') == std::string::npos,
315 "Help export does not currently work with binary names with dashes");
318 void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
320 GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
321 "Attempted to register a duplicate module name");
322 ensureHelpModuleExists();
323 HelpTopicPointer helpTopic(helpModule_->createModuleHelpTopic(*module));
324 modules_.insert(std::make_pair(std::string(module->name()),
326 helpModule_->addTopic(move(helpTopic));
329 void CommandLineModuleManager::Impl::ensureHelpModuleExists()
331 if (helpModule_ == NULL)
333 helpModule_ = new CommandLineHelpModule(programContext_, binaryName_,
334 modules_, moduleGroups_);
335 addModule(CommandLineModulePointer(helpModule_));
339 CommandLineModuleMap::const_iterator
340 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
342 // TODO: Accept unambiguous prefixes?
343 return modules_.find(name);
346 CommandLineModuleMap::const_iterator
347 CommandLineModuleManager::Impl::findModuleFromBinaryName(
348 const char *invokedName) const
350 std::string moduleName = invokedName;
351 #ifdef GMX_BINARY_SUFFIX
352 moduleName = stripSuffixIfPresent(moduleName, GMX_BINARY_SUFFIX);
354 if (moduleName == binaryName_)
356 return modules_.end();
358 if (startsWith(moduleName, "g_"))
360 moduleName.erase(0, 2);
362 if (startsWith(moduleName, "gmx"))
364 moduleName.erase(0, 3);
366 return findModuleByName(moduleName);
369 CommandLineModuleInterface *
370 CommandLineModuleManager::Impl::processCommonOptions(
371 CommandLineCommonOptionsHolder *optionsHolder, int *argc, char ***argv)
373 // Check if we are directly invoking a certain module.
374 CommandLineModuleInterface *module = singleModule_;
377 // Also check for invokation through named symlinks.
378 CommandLineModuleMap::const_iterator moduleIter
379 = findModuleFromBinaryName(programContext_.programName());
380 if (moduleIter != modules_.end())
382 module = moduleIter->second.get();
386 // TODO: It would be nice to propagate at least the -quiet option to
387 // the modules so that they can also be quiet in response to this.
391 // If not in single-module mode, process options to the wrapper binary.
392 // TODO: Ideally, this could be done by CommandLineParser.
393 int argcForWrapper = 1;
394 while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
398 if (argcForWrapper > 1)
400 CommandLineParser(optionsHolder->options())
401 .parse(&argcForWrapper, *argv);
403 // If no action requested and there is a module specified, process it.
404 if (argcForWrapper < *argc && !optionsHolder->shouldIgnoreActualModule())
406 const char *moduleName = (*argv)[argcForWrapper];
407 CommandLineModuleMap::const_iterator moduleIter
408 = findModuleByName(moduleName);
409 if (moduleIter == modules_.end())
411 std::string message =
412 formatString("'%s' is not a GROMACS command.", moduleName);
413 GMX_THROW(InvalidInputError(message));
415 module = moduleIter->second.get();
416 *argc -= argcForWrapper;
417 *argv += argcForWrapper;
418 // After this point, argc and argv are the same independent of
419 // which path is taken: (*argv)[0] is the module name.
424 if (singleModule_ == NULL)
426 programContext_.setDisplayName(binaryName_ + " " + module->name());
428 // Recognize the common options also after the module name.
429 // TODO: It could be nicer to only recognize -h/-hidden if module is not
431 CommandLineParser(optionsHolder->options())
432 .skipUnknown(true).parse(argc, *argv);
434 if (!optionsHolder->finishOptions())
438 // If no module specified and no other action, show the help.
439 // Also explicitly specifying -h for the wrapper binary goes here.
440 if (module == NULL || optionsHolder->shouldShowHelp())
442 ensureHelpModuleExists();
445 helpModule_->setModuleOverride(*module);
448 module = helpModule_;
450 if (module == helpModule_)
452 helpModule_->setShowHidden(optionsHolder->shouldShowHidden());
457 /********************************************************************
458 * CommandLineModuleManager
461 CommandLineModuleManager::CommandLineModuleManager(
462 const char *binaryName, CommandLineProgramContext *programContext)
463 : impl_(new Impl(binaryName, programContext))
467 CommandLineModuleManager::~CommandLineModuleManager()
471 void CommandLineModuleManager::setQuiet(bool bQuiet)
473 impl_->bQuiet_ = bQuiet;
476 void CommandLineModuleManager::setOutputRedirect(File *output)
478 impl_->ensureHelpModuleExists();
479 impl_->helpModule_->setOutputRedirect(output);
482 void CommandLineModuleManager::setSingleModule(CommandLineModuleInterface *module)
484 impl_->singleModule_ = module;
487 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
489 impl_->addModule(move(module));
492 void CommandLineModuleManager::addModuleCMain(
493 const char *name, const char *shortDescription,
494 CMainFunction mainFunction)
496 CommandLineModulePointer module(
497 new CMainCommandLineModule(name, shortDescription, mainFunction));
498 addModule(move(module));
501 CommandLineModuleGroup CommandLineModuleManager::addModuleGroup(
504 const char *const binaryName = impl_->binaryName_.c_str();
505 CommandLineModuleGroupDataPointer group(
506 new CommandLineModuleGroupData(impl_->modules_, binaryName, title));
507 impl_->moduleGroups_.push_back(move(group));
508 return CommandLineModuleGroup(impl_->moduleGroups_.back().get());
511 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
513 impl_->ensureHelpModuleExists();
514 impl_->helpModule_->addTopic(move(topic));
517 int CommandLineModuleManager::run(int argc, char *argv[])
519 CommandLineModuleInterface *module;
520 const bool bMaster = (gmx_node_rank() == 0);
521 bool bQuiet = impl_->bQuiet_ || !bMaster;
522 CommandLineCommonOptionsHolder optionsHolder;
525 optionsHolder.initOptions();
526 module = impl_->processCommonOptions(&optionsHolder, &argc, &argv);
528 catch (const std::exception &)
530 bQuiet |= optionsHolder.shouldBeQuiet();
533 printBinaryInformation(stderr, impl_->programContext_,
534 optionsHolder.binaryInfoSettings());
538 bQuiet |= optionsHolder.shouldBeQuiet();
541 FILE *out = optionsHolder.startupInfoFile();
542 printBinaryInformation(out, impl_->programContext_,
543 optionsHolder.binaryInfoSettings());
550 /* Open the debug file */
551 if (optionsHolder.debugLevel() > 0)
553 std::string filename(impl_->programContext_.programName());
554 if (gmx_node_num() > 1)
556 filename.append(formatString("%d", gmx_node_rank()));
558 filename.append(".debug");
560 fprintf(stderr, "Will write debug log file: %s\n", filename.c_str());
561 gmx_init_debug(optionsHolder.debugLevel(), filename.c_str());
564 if (!(module == impl_->helpModule_ && !bMaster))
566 rc = module->run(argc, argv);
576 int CommandLineModuleManager::runAsMainSingleModule(
577 int argc, char *argv[], CommandLineModuleInterface *module)
579 CommandLineProgramContext &programContext = gmx::initForCommandLine(&argc, &argv);
582 CommandLineModuleManager manager(NULL, &programContext);
583 manager.setSingleModule(module);
584 int rc = manager.run(argc, argv);
585 gmx::finalizeForCommandLine();
588 catch (const std::exception &ex)
590 printFatalErrorMessage(stderr, ex);
591 return processExceptionAtExit(ex);
596 int CommandLineModuleManager::runAsMainCMain(
597 int argc, char *argv[], CMainFunction mainFunction)
599 CMainCommandLineModule module(argv[0], NULL, mainFunction);
600 return runAsMainSingleModule(argc, argv, &module);
603 /********************************************************************
604 * CommandLineModuleGroupData
607 void CommandLineModuleGroupData::addModule(const char *name,
608 const char *description)
610 CommandLineModuleMap::const_iterator moduleIter = allModules_.find(name);
611 GMX_RELEASE_ASSERT(moduleIter != allModules_.end(),
612 "Non-existent module added to a group");
613 if (description == NULL)
615 description = moduleIter->second->shortDescription();
616 GMX_RELEASE_ASSERT(description != NULL,
617 "Module without a description added to a group");
619 std::string tag(formatString("%s-%s", binaryName_, name));
620 modules_.push_back(std::make_pair(tag, description));
623 /********************************************************************
624 * CommandLineModuleGroup
627 void CommandLineModuleGroup::addModule(const char *name)
629 impl_->addModule(name, NULL);
632 void CommandLineModuleGroup::addModuleWithDescription(const char *name,
633 const char *description)
635 impl_->addModule(name, description);