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"
50 #include "gromacs/legacyheaders/network.h"
52 #include "gromacs/commandline/cmdlinehelpcontext.h"
53 #include "gromacs/commandline/cmdlinehelpmodule.h"
54 #include "gromacs/commandline/cmdlinemodule.h"
55 #include "gromacs/commandline/cmdlinemodulemanager-impl.h"
56 #include "gromacs/commandline/cmdlineparser.h"
57 #include "gromacs/options/basicoptions.h"
58 #include "gromacs/options/options.h"
59 #include "gromacs/utility/exceptions.h"
60 #include "gromacs/utility/gmxassert.h"
61 #include "gromacs/utility/init.h"
62 #include "gromacs/utility/programinfo.h"
63 #include "gromacs/utility/stringutil.h"
71 /********************************************************************
72 * CMainCommandLineModule
76 * Implements a CommandLineModuleInterface, given a function with C/C++ main()
79 * \ingroup module_commandline
81 class CMainCommandLineModule : public CommandLineModuleInterface
84 //! \copydoc gmx::CommandLineModuleManager::CMainFunction
85 typedef CommandLineModuleManager::CMainFunction CMainFunction;
88 * Creates a wrapper module for the given main function.
90 * \param[in] name Name for the module.
91 * \param[in] shortDescription One-line description for the module.
92 * \param[in] mainFunction Main function to wrap.
94 * Does not throw. This is essential for correct implementation of
95 * CommandLineModuleManager::runAsMainCMain().
97 CMainCommandLineModule(const char *name, const char *shortDescription,
98 CMainFunction mainFunction)
99 : name_(name), shortDescription_(shortDescription),
100 mainFunction_(mainFunction)
104 virtual const char *name() const
108 virtual const char *shortDescription() const
110 return shortDescription_;
113 virtual int run(int argc, char *argv[])
115 return mainFunction_(argc, argv);
117 virtual void writeHelp(const CommandLineHelpContext &context) const
121 // TODO: The constness should not be cast away.
122 argv[0] = const_cast<char *>(name_);
124 GlobalCommandLineHelpContext global(context);
125 mainFunction_(argc, argv);
130 const char *shortDescription_;
131 CMainFunction mainFunction_;
137 /********************************************************************
138 * CommandLineModuleManager::Impl
142 * Private implementation class for CommandLineModuleManager.
144 * \ingroup module_commandline
146 class CommandLineModuleManager::Impl
150 * Initializes the implementation class.
152 * \param programInfo Program information for the running binary.
154 explicit Impl(ProgramInfo *programInfo);
157 * Helper method that adds a given module to the module manager.
159 * \throws std::bad_alloc if out of memory.
161 void addModule(CommandLineModulePointer module);
163 * Creates the help module if it does not yet exist.
165 * \throws std::bad_alloc if out of memory.
167 * This method should be called before accessing \a helpModule_.
169 void ensureHelpModuleExists();
172 * Finds a module that matches a name.
174 * \param[in] name Module name to find.
175 * \returns Iterator to the found module, or
176 * \c modules_.end() if not found.
180 CommandLineModuleMap::const_iterator
181 findModuleByName(const std::string &name) const;
183 * Finds a module that the name of the binary.
185 * \param[in] programInfo Program information object to use.
186 * \throws std::bad_alloc if out of memory.
187 * \returns Iterator to the found module, or
188 * \c modules_.end() if not found.
190 * Checks whether the program is invoked through a symlink whose name
191 * is different from ProgramInfo::realBinaryName(), and if so, checks
192 * if a module name matches the name of the symlink.
194 * Note that the \p programInfo parameter is currently not necessary
195 * (as the program info object is also contained as a member), but it
196 * clarifies the control flow.
198 CommandLineModuleMap::const_iterator
199 findModuleFromBinaryName(const ProgramInfo &programInfo) const;
202 * Processes command-line options for the wrapper binary.
204 * \param[in,out] argc On input, argc passed to run().
205 * On output, argc to be passed to the module.
206 * \param[in,out] argv On input, argv passed to run().
207 * On output, argv to be passed to the module.
208 * \throws InvalidInputError if there are invalid options.
209 * \returns The module that should be run.
211 * Handles command-line options that affect the wrapper binary
212 * (potentially changing the members of \c this in response to the
213 * options). Also finds the module that should be run and the
214 * arguments that should be passed to it.
216 CommandLineModuleInterface *
217 processCommonOptions(int *argc, char ***argv);
220 * Maps module names to module objects.
222 * Owns the contained modules.
224 CommandLineModuleMap modules_;
226 * List of groupings for modules for help output.
228 * Owns the contained module group data objects.
229 * CommandLineModuleGroup objects point to the data objects contained
232 CommandLineModuleGroupList moduleGroups_;
233 //! Information about the currently running program.
234 ProgramInfo &programInfo_;
236 * Module that implements help for the binary.
238 * The pointed module is owned by the \a modules_ container.
240 CommandLineHelpModule *helpModule_;
241 //! Settings for what to write in the startup header.
242 BinaryInformationSettings binaryInfoSettings_;
243 //! If non-NULL, run this module in single-module mode.
244 CommandLineModuleInterface *singleModule_;
245 //! Whether all stderr output should be suppressed.
247 //! Whether to write the startup information to stdout iso stderr.
251 GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
254 CommandLineModuleManager::Impl::Impl(ProgramInfo *programInfo)
255 : programInfo_(*programInfo), helpModule_(NULL), singleModule_(NULL),
256 bQuiet_(false), bStdOutInfo_(false)
258 binaryInfoSettings_.copyright(true);
261 void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
263 GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
264 "Attempted to register a duplicate module name");
265 ensureHelpModuleExists();
266 HelpTopicPointer helpTopic(helpModule_->createModuleHelpTopic(*module));
267 modules_.insert(std::make_pair(std::string(module->name()),
269 helpModule_->addTopic(move(helpTopic));
272 void CommandLineModuleManager::Impl::ensureHelpModuleExists()
274 if (helpModule_ == NULL)
276 helpModule_ = new CommandLineHelpModule(programInfo_, modules_,
278 addModule(CommandLineModulePointer(helpModule_));
282 CommandLineModuleMap::const_iterator
283 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
285 // TODO: Accept unambiguous prefixes?
286 return modules_.find(name);
289 CommandLineModuleMap::const_iterator
290 CommandLineModuleManager::Impl::findModuleFromBinaryName(
291 const ProgramInfo &programInfo) const
293 std::string binaryName = programInfo.invariantProgramName();
294 if (binaryName == programInfo.realBinaryName())
296 return modules_.end();
298 if (binaryName.compare(0, 2, "g_") == 0)
300 binaryName.erase(0, 2);
302 if (binaryName.compare(0, 3, "gmx") == 0)
304 binaryName.erase(0, 3);
306 return findModuleByName(binaryName);
309 CommandLineModuleInterface *
310 CommandLineModuleManager::Impl::processCommonOptions(int *argc, char ***argv)
312 // Check if we are directly invoking a certain module.
313 CommandLineModuleInterface *module = singleModule_;
316 // Also check for invokation through named symlinks.
317 CommandLineModuleMap::const_iterator moduleIter
318 = findModuleFromBinaryName(programInfo_);
319 if (moduleIter != modules_.end())
321 module = moduleIter->second.get();
326 bool bHidden = false;
327 bool bVersion = false;
328 bool bCopyright = true;
329 // TODO: Print the common options into the help.
330 // TODO: It would be nice to propagate at least the -quiet option to
331 // the modules so that they can also be quiet in response to this.
332 Options options(NULL, NULL);
333 options.addOption(BooleanOption("h").store(&bHelp));
334 options.addOption(BooleanOption("hidden").store(&bHidden));
335 options.addOption(BooleanOption("quiet").store(&bQuiet_));
336 options.addOption(BooleanOption("version").store(&bVersion));
337 options.addOption(BooleanOption("copyright").store(&bCopyright));
341 // If not in single-module mode, process options to the wrapper binary.
342 // TODO: Ideally, this could be done by CommandLineParser.
343 int argcForWrapper = 1;
344 while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
348 if (argcForWrapper > 1)
350 CommandLineParser(&options).parse(&argcForWrapper, *argv);
352 // If no action requested and there is a module specified, process it.
353 if (argcForWrapper < *argc && !bHelp && !bVersion)
355 const char *moduleName = (*argv)[argcForWrapper];
356 CommandLineModuleMap::const_iterator moduleIter
357 = findModuleByName(moduleName);
358 if (moduleIter == modules_.end())
360 std::string message =
361 formatString("'%s' is not a GROMACS command.", moduleName);
362 GMX_THROW(InvalidInputError(message));
364 module = moduleIter->second.get();
365 *argc -= argcForWrapper;
366 *argv += argcForWrapper;
367 // After this point, argc and argv are the same independent of
368 // which path is taken: (*argv)[0] is the module name.
373 if (singleModule_ == NULL)
375 programInfo_.setDisplayName(
376 programInfo_.realBinaryName() + " " + module->name());
378 // Recognize the common options also after the module name.
379 // TODO: It could be nicer to only recognize -h/-hidden if module is not
381 CommandLineParser(&options).skipUnknown(true).parse(argc, *argv);
384 binaryInfoSettings_.extendedInfo(bVersion);
385 binaryInfoSettings_.copyright(bCopyright);
392 // If no module specified and no other action, show the help.
393 // Also explicitly specifying -h for the wrapper binary goes here.
394 if (module == NULL || bHelp)
396 ensureHelpModuleExists();
399 helpModule_->setModuleOverride(*module);
402 module = helpModule_;
404 if (module == helpModule_)
406 helpModule_->setShowHidden(bHidden);
411 /********************************************************************
412 * CommandLineModuleManager
415 CommandLineModuleManager::CommandLineModuleManager(ProgramInfo *programInfo)
416 : impl_(new Impl(programInfo))
420 CommandLineModuleManager::~CommandLineModuleManager()
424 void CommandLineModuleManager::setQuiet(bool bQuiet)
426 impl_->bQuiet_ = bQuiet;
429 void CommandLineModuleManager::setSingleModule(CommandLineModuleInterface *module)
431 impl_->singleModule_ = module;
434 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
436 impl_->addModule(move(module));
439 void CommandLineModuleManager::addModuleCMain(
440 const char *name, const char *shortDescription,
441 CMainFunction mainFunction)
443 CommandLineModulePointer module(
444 new CMainCommandLineModule(name, shortDescription, mainFunction));
445 addModule(move(module));
448 CommandLineModuleGroup CommandLineModuleManager::addModuleGroup(
451 CommandLineModuleGroupDataPointer group(
452 new CommandLineModuleGroupData(impl_->modules_, title));
453 impl_->moduleGroups_.push_back(move(group));
454 return CommandLineModuleGroup(impl_->moduleGroups_.back().get());
457 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
459 impl_->ensureHelpModuleExists();
460 impl_->helpModule_->addTopic(move(topic));
463 int CommandLineModuleManager::run(int argc, char *argv[])
465 CommandLineModuleInterface *module;
466 const bool bMaster = (!gmx_mpi_initialized() || gmx_node_rank() == 0);
469 module = impl_->processCommonOptions(&argc, &argv);
471 catch (const std::exception &)
473 if (bMaster && !impl_->bQuiet_)
475 printBinaryInformation(stderr, impl_->programInfo_,
476 impl_->binaryInfoSettings_);
482 impl_->bQuiet_ = true;
486 FILE *out = (impl_->bStdOutInfo_ ? stdout : stderr);
487 printBinaryInformation(out, impl_->programInfo_,
488 impl_->binaryInfoSettings_);
495 int rc = module->run(argc, argv);
504 int CommandLineModuleManager::runAsMainSingleModule(
505 int argc, char *argv[], CommandLineModuleInterface *module)
507 ProgramInfo &programInfo = gmx::init(&argc, &argv);
510 CommandLineModuleManager manager(&programInfo);
511 manager.setSingleModule(module);
512 int rc = manager.run(argc, argv);
516 catch (const std::exception &ex)
518 printFatalErrorMessage(stderr, ex);
519 return processExceptionAtExit(ex);
524 int CommandLineModuleManager::runAsMainCMain(
525 int argc, char *argv[], CMainFunction mainFunction)
527 CMainCommandLineModule module(argv[0], NULL, mainFunction);
528 return runAsMainSingleModule(argc, argv, &module);
531 /********************************************************************
532 * CommandLineModuleGroupData
535 void CommandLineModuleGroupData::addModule(const char *name,
536 const char *description)
538 CommandLineModuleMap::const_iterator moduleIter = allModules_.find(name);
539 GMX_RELEASE_ASSERT(moduleIter != allModules_.end(),
540 "Non-existent module added to a group");
541 if (description == NULL)
543 description = moduleIter->second->shortDescription();
544 GMX_RELEASE_ASSERT(description != NULL,
545 "Module without a description added to a group");
547 const char *const program =
548 ProgramInfo::getInstance().invariantProgramName().c_str();
549 std::string tag(formatString("%s-%s", program, name));
550 modules_.push_back(std::make_pair(tag, description));
553 /********************************************************************
554 * CommandLineModuleGroup
557 void CommandLineModuleGroup::addModule(const char *name)
559 impl_->addModule(name, NULL);
562 void CommandLineModuleGroup::addModuleWithDescription(const char *name,
563 const char *description)
565 impl_->addModule(name, description);