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
44 #include "cmdlinemodulemanager.h"
53 #include "gromacs/commandline/cmdlinehelpcontext.h"
54 #include "gromacs/commandline/cmdlineinit.h"
55 #include "gromacs/commandline/cmdlinemodule.h"
56 #include "gromacs/commandline/cmdlineparser.h"
57 #include "gromacs/commandline/cmdlineprogramcontext.h"
58 #include "gromacs/legacyheaders/copyrite.h"
59 #include "gromacs/options/basicoptions.h"
60 #include "gromacs/options/options.h"
61 #include "gromacs/utility/basenetwork.h"
62 #include "gromacs/utility/exceptions.h"
63 #include "gromacs/utility/fatalerror.h"
64 #include "gromacs/utility/gmxassert.h"
65 #include "gromacs/utility/stringutil.h"
66 #include "gromacs/utility/sysinfo.h"
68 #include "cmdlinehelpmodule.h"
69 #include "cmdlinemodulemanager-impl.h"
77 //! \addtogroup module_commandline
80 /********************************************************************
81 * CMainCommandLineModule
85 * Implements a CommandLineModuleInterface, given a function with C/C++ main()
88 class CMainCommandLineModule : public CommandLineModuleInterface
91 //! \copydoc gmx::CommandLineModuleManager::CMainFunction
92 typedef CommandLineModuleManager::CMainFunction CMainFunction;
95 * Creates a wrapper module for the given main function.
97 * \param[in] name Name for the module.
98 * \param[in] shortDescription One-line description for the module.
99 * \param[in] mainFunction Main function to wrap.
101 * Does not throw. This is essential for correct implementation of
102 * CommandLineModuleManager::runAsMainCMain().
104 CMainCommandLineModule(const char *name, const char *shortDescription,
105 CMainFunction mainFunction)
106 : name_(name), shortDescription_(shortDescription),
107 mainFunction_(mainFunction)
111 virtual const char *name() const
115 virtual const char *shortDescription() const
117 return shortDescription_;
120 virtual void init(CommandLineModuleSettings * /*settings*/)
123 virtual int run(int argc, char *argv[])
125 return mainFunction_(argc, argv);
127 virtual void writeHelp(const CommandLineHelpContext &context) const
129 writeCommandLineHelpCMain(context, name_, mainFunction_);
134 const char *shortDescription_;
135 CMainFunction mainFunction_;
142 /********************************************************************
143 * CommandLineCommonOptionsHolder
146 CommandLineCommonOptionsHolder::CommandLineCommonOptionsHolder()
147 : options_(NULL, NULL), bHelp_(false), bHidden_(false),
148 bQuiet_(false), bVersion_(false), bCopyright_(true),
149 niceLevel_(19), debugLevel_(0)
151 binaryInfoSettings_.copyright(true);
154 CommandLineCommonOptionsHolder::~CommandLineCommonOptionsHolder()
158 void CommandLineCommonOptionsHolder::initOptions()
160 options_.addOption(BooleanOption("h").store(&bHelp_)
161 .description("Print help and quit"));
162 options_.addOption(BooleanOption("hidden").store(&bHidden_)
164 .description("Show hidden options in help"));
165 options_.addOption(BooleanOption("quiet").store(&bQuiet_)
166 .description("Do not print common startup info or quotes"));
167 options_.addOption(BooleanOption("version").store(&bVersion_)
168 .description("Print extended version information and quit"));
169 options_.addOption(BooleanOption("copyright").store(&bCopyright_)
170 .description("Print copyright information on startup"));
171 options_.addOption(IntegerOption("nice").store(&niceLevel_)
172 .description("Set the nicelevel (default depends on command)"));
173 options_.addOption(IntegerOption("debug").store(&debugLevel_)
174 .hidden().defaultValueIfSet(1)
175 .description("Write file with debug information, "
176 "1: short (default), 2: also x and f"));
179 bool CommandLineCommonOptionsHolder::finishOptions()
182 binaryInfoSettings_.extendedInfo(bVersion_);
183 // The latter condition suppresses the copyright with
185 binaryInfoSettings_.copyright(bCopyright_ && !bQuiet_);
189 void CommandLineCommonOptionsHolder::adjustFromSettings(
190 const CommandLineModuleSettings &settings)
192 if (!options_.isSet("nice"))
194 niceLevel_ = settings.defaultNiceLevel();
198 /********************************************************************
199 * CommandLineModuleManager::Impl
203 * Private implementation class for CommandLineModuleManager.
205 * \ingroup module_commandline
207 class CommandLineModuleManager::Impl
211 * Initializes the implementation class.
213 * \param[in] binaryName Name of the running binary
214 * (without Gromacs binary suffix or .exe on Windows).
215 * \param programContext Program information for the running binary.
217 Impl(const char *binaryName, CommandLineProgramContext *programContext);
220 * Helper method that adds a given module to the module manager.
222 * \throws std::bad_alloc if out of memory.
224 void addModule(CommandLineModulePointer module);
226 * Creates the help module if it does not yet exist.
228 * \throws std::bad_alloc if out of memory.
230 * This method should be called before accessing \a helpModule_.
232 void ensureHelpModuleExists();
235 * Finds a module that matches a name.
237 * \param[in] name Module name to find.
238 * \returns Iterator to the found module, or
239 * \c modules_.end() if not found.
243 CommandLineModuleMap::const_iterator
244 findModuleByName(const std::string &name) const;
246 * Finds a module that the name of the binary.
248 * \param[in] invokedName Name by which the program was invoked.
249 * \throws std::bad_alloc if out of memory.
250 * \returns Iterator to the found module, or
251 * \c modules_.end() if not found.
253 * Checks whether the program is invoked through a symlink whose name
254 * is different from \a binaryName_, and if so, checks
255 * if a module name matches the name of the symlink.
257 * Note that the \p invokedName parameter is currently not necessary
258 * (as the program context object is also available and provides this
259 * value), but it clarifies the control flow.
261 CommandLineModuleMap::const_iterator
262 findModuleFromBinaryName(const char *invokedName) const;
265 * Processes command-line options for the wrapper binary.
267 * \param[in,out] optionsHolder Common options.
268 * \param[in,out] argc On input, argc passed to run().
269 * On output, argc to be passed to the module.
270 * \param[in,out] argv On input, argv passed to run().
271 * On output, argv to be passed to the module.
272 * \throws InvalidInputError if there are invalid options.
273 * \returns The module that should be run.
275 * Handles command-line options that affect the wrapper binary
276 * (potentially changing the members of \c this in response to the
277 * options). Also finds the module that should be run and the
278 * arguments that should be passed to it.
280 CommandLineModuleInterface *
281 processCommonOptions(CommandLineCommonOptionsHolder *optionsHolder,
282 int *argc, char ***argv);
285 * Maps module names to module objects.
287 * Owns the contained modules.
289 CommandLineModuleMap modules_;
291 * List of groupings for modules for help output.
293 * Owns the contained module group data objects.
294 * CommandLineModuleGroup objects point to the data objects contained
297 CommandLineModuleGroupList moduleGroups_;
298 //! Information about the currently running program.
299 CommandLineProgramContext &programContext_;
300 //! Name of the binary.
301 std::string binaryName_;
303 * Module that implements help for the binary.
305 * The pointed module is owned by the \a modules_ container.
307 CommandLineHelpModule *helpModule_;
308 //! If non-NULL, run this module in single-module mode.
309 CommandLineModuleInterface *singleModule_;
310 //! Stores the value set with setQuiet().
314 GMX_DISALLOW_COPY_AND_ASSIGN(Impl);
317 CommandLineModuleManager::Impl::Impl(const char *binaryName,
318 CommandLineProgramContext *programContext)
319 : programContext_(*programContext),
320 binaryName_(binaryName != NULL ? binaryName : ""),
321 helpModule_(NULL), singleModule_(NULL),
324 GMX_RELEASE_ASSERT(binaryName_.find('-') == std::string::npos,
325 "Help export does not currently work with binary names with dashes");
328 void CommandLineModuleManager::Impl::addModule(CommandLineModulePointer module)
330 GMX_ASSERT(modules_.find(module->name()) == modules_.end(),
331 "Attempted to register a duplicate module name");
332 ensureHelpModuleExists();
333 HelpTopicPointer helpTopic(helpModule_->createModuleHelpTopic(*module));
334 modules_.insert(std::make_pair(std::string(module->name()),
336 helpModule_->addTopic(move(helpTopic));
339 void CommandLineModuleManager::Impl::ensureHelpModuleExists()
341 if (helpModule_ == NULL)
343 helpModule_ = new CommandLineHelpModule(programContext_, binaryName_,
344 modules_, moduleGroups_);
345 addModule(CommandLineModulePointer(helpModule_));
349 CommandLineModuleMap::const_iterator
350 CommandLineModuleManager::Impl::findModuleByName(const std::string &name) const
352 // TODO: Accept unambiguous prefixes?
353 return modules_.find(name);
356 CommandLineModuleMap::const_iterator
357 CommandLineModuleManager::Impl::findModuleFromBinaryName(
358 const char *invokedName) const
360 std::string moduleName = invokedName;
361 #ifdef GMX_BINARY_SUFFIX
362 moduleName = stripSuffixIfPresent(moduleName, GMX_BINARY_SUFFIX);
364 if (moduleName == binaryName_)
366 return modules_.end();
368 if (startsWith(moduleName, "g_"))
370 moduleName.erase(0, 2);
372 if (startsWith(moduleName, "gmx"))
374 moduleName.erase(0, 3);
376 return findModuleByName(moduleName);
379 CommandLineModuleInterface *
380 CommandLineModuleManager::Impl::processCommonOptions(
381 CommandLineCommonOptionsHolder *optionsHolder, int *argc, char ***argv)
383 // Check if we are directly invoking a certain module.
384 CommandLineModuleInterface *module = singleModule_;
387 // Also check for invokation through named symlinks.
388 CommandLineModuleMap::const_iterator moduleIter
389 = findModuleFromBinaryName(programContext_.programName());
390 if (moduleIter != modules_.end())
392 module = moduleIter->second.get();
396 // TODO: It would be nice to propagate at least the -quiet option to
397 // the modules so that they can also be quiet in response to this.
401 // If not in single-module mode, process options to the wrapper binary.
402 // TODO: Ideally, this could be done by CommandLineParser.
403 int argcForWrapper = 1;
404 while (argcForWrapper < *argc && (*argv)[argcForWrapper][0] == '-')
408 if (argcForWrapper > 1)
410 CommandLineParser(optionsHolder->options())
411 .parse(&argcForWrapper, *argv);
413 // If no action requested and there is a module specified, process it.
414 if (argcForWrapper < *argc && !optionsHolder->shouldIgnoreActualModule())
416 const char *moduleName = (*argv)[argcForWrapper];
417 CommandLineModuleMap::const_iterator moduleIter
418 = findModuleByName(moduleName);
419 if (moduleIter == modules_.end())
421 std::string message =
422 formatString("'%s' is not a GROMACS command.", moduleName);
423 GMX_THROW(InvalidInputError(message));
425 module = moduleIter->second.get();
426 *argc -= argcForWrapper;
427 *argv += argcForWrapper;
428 // After this point, argc and argv are the same independent of
429 // which path is taken: (*argv)[0] is the module name.
434 if (singleModule_ == NULL)
436 programContext_.setDisplayName(binaryName_ + " " + module->name());
438 // Recognize the common options also after the module name.
439 // TODO: It could be nicer to only recognize -h/-hidden if module is not
441 CommandLineParser(optionsHolder->options())
442 .skipUnknown(true).parse(argc, *argv);
444 if (!optionsHolder->finishOptions())
448 // If no module specified and no other action, show the help.
449 // Also explicitly specifying -h for the wrapper binary goes here.
450 if (module == NULL || optionsHolder->shouldShowHelp())
452 ensureHelpModuleExists();
455 helpModule_->setModuleOverride(*module);
458 module = helpModule_;
460 if (module == helpModule_)
462 helpModule_->setShowHidden(optionsHolder->shouldShowHidden());
467 /********************************************************************
468 * CommandLineModuleManager
471 CommandLineModuleManager::CommandLineModuleManager(
472 const char *binaryName, CommandLineProgramContext *programContext)
473 : impl_(new Impl(binaryName, programContext))
477 CommandLineModuleManager::~CommandLineModuleManager()
481 void CommandLineModuleManager::setQuiet(bool bQuiet)
483 impl_->bQuiet_ = bQuiet;
486 void CommandLineModuleManager::setOutputRedirect(File *output)
488 impl_->ensureHelpModuleExists();
489 impl_->helpModule_->setOutputRedirect(output);
492 void CommandLineModuleManager::setSingleModule(CommandLineModuleInterface *module)
494 impl_->singleModule_ = module;
497 void CommandLineModuleManager::addModule(CommandLineModulePointer module)
499 impl_->addModule(move(module));
502 void CommandLineModuleManager::addModuleCMain(
503 const char *name, const char *shortDescription,
504 CMainFunction mainFunction)
506 CommandLineModulePointer module(
507 new CMainCommandLineModule(name, shortDescription, mainFunction));
508 addModule(move(module));
511 CommandLineModuleGroup CommandLineModuleManager::addModuleGroup(
514 const char *const binaryName = impl_->binaryName_.c_str();
515 CommandLineModuleGroupDataPointer group(
516 new CommandLineModuleGroupData(impl_->modules_, binaryName, title));
517 impl_->moduleGroups_.push_back(move(group));
518 return CommandLineModuleGroup(impl_->moduleGroups_.back().get());
521 void CommandLineModuleManager::addHelpTopic(HelpTopicPointer topic)
523 impl_->ensureHelpModuleExists();
524 impl_->helpModule_->addTopic(move(topic));
527 int CommandLineModuleManager::run(int argc, char *argv[])
529 CommandLineModuleInterface *module;
530 const bool bMaster = (gmx_node_rank() == 0);
531 bool bQuiet = impl_->bQuiet_ || !bMaster;
532 CommandLineCommonOptionsHolder optionsHolder;
535 optionsHolder.initOptions();
536 module = impl_->processCommonOptions(&optionsHolder, &argc, &argv);
538 catch (const std::exception &)
540 bQuiet |= optionsHolder.shouldBeQuiet();
543 printBinaryInformation(stderr, impl_->programContext_,
544 optionsHolder.binaryInfoSettings());
548 bQuiet |= optionsHolder.shouldBeQuiet();
551 FILE *out = optionsHolder.startupInfoFile();
552 printBinaryInformation(out, impl_->programContext_,
553 optionsHolder.binaryInfoSettings());
561 CommandLineModuleSettings settings;
562 module->init(&settings);
563 optionsHolder.adjustFromSettings(settings);
565 // Open the debug file.
566 if (optionsHolder.debugLevel() > 0)
568 std::string filename(impl_->programContext_.programName());
569 if (gmx_node_num() > 1)
571 filename.append(formatString("%d", gmx_node_rank()));
573 filename.append(".debug");
575 fprintf(stderr, "Will write debug log file: %s\n", filename.c_str());
576 gmx_init_debug(optionsHolder.debugLevel(), filename.c_str());
578 // Set the nice level unless disabled in the configuration.
579 if (optionsHolder.niceLevel() != 0)
581 static bool bNiceSet = false; // Only set it once.
584 // TODO: Diagnostic if this fails and the user explicitly requested it.
585 gmx_set_nice(optionsHolder.niceLevel());
591 if (!(module == impl_->helpModule_ && !bMaster))
593 rc = module->run(argc, argv);
603 int CommandLineModuleManager::runAsMainSingleModule(
604 int argc, char *argv[], CommandLineModuleInterface *module)
606 CommandLineProgramContext &programContext = gmx::initForCommandLine(&argc, &argv);
609 CommandLineModuleManager manager(NULL, &programContext);
610 manager.setSingleModule(module);
611 int rc = manager.run(argc, argv);
612 gmx::finalizeForCommandLine();
615 catch (const std::exception &ex)
617 printFatalErrorMessage(stderr, ex);
618 return processExceptionAtExitForCommandLine(ex);
623 int CommandLineModuleManager::runAsMainCMain(
624 int argc, char *argv[], CMainFunction mainFunction)
626 CMainCommandLineModule module(argv[0], NULL, mainFunction);
627 return runAsMainSingleModule(argc, argv, &module);
630 /********************************************************************
631 * CommandLineModuleGroupData
634 void CommandLineModuleGroupData::addModule(const char *name,
635 const char *description)
637 CommandLineModuleMap::const_iterator moduleIter = allModules_.find(name);
638 GMX_RELEASE_ASSERT(moduleIter != allModules_.end(),
639 "Non-existent module added to a group");
640 if (description == NULL)
642 description = moduleIter->second->shortDescription();
643 GMX_RELEASE_ASSERT(description != NULL,
644 "Module without a description added to a group");
646 std::string tag(formatString("%s-%s", binaryName_, name));
647 modules_.push_back(std::make_pair(tag, description));
650 /********************************************************************
651 * CommandLineModuleGroup
654 void CommandLineModuleGroup::addModule(const char *name)
656 impl_->addModule(name, NULL);
659 void CommandLineModuleGroup::addModuleWithDescription(const char *name,
660 const char *description)
662 impl_->addModule(name, description);