2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010-2018, The GROMACS development team.
5 * Copyright (c) 2019,2020,2021, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
38 * Implements gmx::CommandLineParser.
40 * \author Teemu Murtola <teemu.murtola@gmail.com>
41 * \ingroup module_commandline
45 #include "cmdlineparser.h"
52 #include "gromacs/options/optionsassigner.h"
53 #include "gromacs/utility/basedefinitions.h"
54 #include "gromacs/utility/exceptions.h"
59 /********************************************************************
60 * CommandLineParser::Impl
64 * Private implementation class for CommandLineParser.
66 * \ingroup module_commandline
68 class CommandLineParser::Impl
71 //! Sets the options object to parse to.
72 explicit Impl(Options* options);
75 * Determines whether a cmdline parameter starts an option and the name
78 * \param[in] arg Individual argument from \c argv.
79 * \returns The beginning of the option name in \p arg, or NULL if
80 * \p arg does not look like an option.
82 static const char* toOptionName(const char* arg);
84 //! Helper object for assigning the options.
85 OptionsAssigner assigner_;
86 //! Whether to allow and skip unknown options.
88 /*! \brief Whether to allow positional arguments
90 * These are not options (no leading hyphen), and come before
92 bool bAllowPositionalArguments_;
95 CommandLineParser::Impl::Impl(Options* options) :
96 assigner_(options), bSkipUnknown_(false), bAllowPositionalArguments_(false)
98 assigner_.setAcceptBooleanNoPrefix(true);
101 const char* CommandLineParser::Impl::toOptionName(const char* arg)
103 // Lone '-' or '--' is not an option.
104 if (arg[0] != '-' || arg[1] == '\0' || (arg[1] == '-' && arg[2] == '\0'))
108 // Something starting with '--' is always an option.
113 // Don't return numbers as option names.
115 // We are only interested in endptr, not in the actual value.
116 GMX_IGNORE_RETURN_VALUE(std::strtod(arg, &endptr));
124 /********************************************************************
128 CommandLineParser::CommandLineParser(Options* options) : impl_(new Impl(options)) {}
130 CommandLineParser::~CommandLineParser() {}
132 CommandLineParser& CommandLineParser::skipUnknown(bool bEnabled)
134 impl_->bSkipUnknown_ = bEnabled;
138 CommandLineParser& CommandLineParser::allowPositionalArguments(bool bEnabled)
140 impl_->bAllowPositionalArguments_ = bEnabled;
144 void CommandLineParser::parse(int* argc, char* argv[])
146 ExceptionInitializer errors("Invalid command-line options");
147 std::string currentContext;
148 bool bInOption = false;
150 // Note that this function gets called multiple times in typical
151 // cases of calling gmx. Command lines like "gmx -hidden mdrun -h"
152 // work because the first call has argv[0] == "gmx" and skips
153 // unknown things, and the second has argv[0] == "mdrun".
156 // First, process any permitted leading positional arguments.
157 for (; i < *argc; ++i)
159 const char* const arg = argv[i];
160 if (impl_->toOptionName(arg) != nullptr)
162 // If we find an option, no more positional arguments
167 if (!impl_->bAllowPositionalArguments_)
171 "Positional argument '" + std::string(arg)
172 + "' cannot be accepted. "
173 "Perhaps you forgot to put a hyphen before an option name."));
175 // argv[i] is not an option, so preserve it in the argument list
176 // by incrementing newi. There's no need to copy argv contents
177 // because they cannot have changed yet.
181 // Now handle the option arguments.
182 impl_->assigner_.start();
183 for (; i < *argc; ++i)
185 const char* const arg = argv[i];
186 const char* const optionName = impl_->toOptionName(arg);
187 if (optionName != nullptr)
193 impl_->assigner_.finishOption();
195 catch (UserInputError& ex)
197 ex.prependContext(currentContext);
198 errors.addCurrentExceptionAsNested();
201 currentContext = "In command-line option " + std::string(arg);
204 bInOption = impl_->assigner_.tryStartOption(optionName);
207 currentContext.clear();
208 if (!impl_->bSkipUnknown_)
210 std::string message = "Unknown command-line option " + std::string(arg);
211 GMX_THROW(InvalidInputError(message));
215 catch (UserInputError& ex)
217 // If tryStartOption() throws, make sure that the rest gets
219 // TODO: Consider whether we should remove the option from the
220 // command line nonetheless, as it is recognized, but just
223 ex.prependContext(currentContext);
224 errors.addCurrentExceptionAsNested();
225 currentContext.clear();
232 impl_->assigner_.appendValue(arg);
234 // TODO: Consider if some types of exceptions would be better left
236 catch (GromacsException& ex)
238 ex.prependContext(currentContext);
239 errors.addCurrentExceptionAsNested();
242 // Retain unrecognized options if applicable.
243 if (!bInOption && impl_->bSkipUnknown_)
245 argv[newi] = argv[i];
249 // Update the args if argv was modified.
250 if (impl_->bSkipUnknown_)
253 argv[newi] = nullptr;
256 // Finish the last option.
261 impl_->assigner_.finishOption();
263 catch (UserInputError& ex)
265 ex.prependContext(currentContext);
266 errors.addCurrentExceptionAsNested();
269 impl_->assigner_.finish();
270 if (errors.hasNestedExceptions())
272 // TODO: This exception type may not always be appropriate.
273 GMX_THROW(InvalidInputError(errors));