Version bumps after new release
[alexxy/gromacs.git] / src / gromacs / commandline / cmdlineparser.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010,2011,2012,2013, 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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements gmx::CommandLineParser.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_commandline
41  */
42 #include "cmdlineparser.h"
43
44 #include <cstdlib>
45
46 #include <string>
47 #include <vector>
48
49 #include "gromacs/options/optionsassigner.h"
50 #include "gromacs/utility/common.h"
51 #include "gromacs/utility/exceptions.h"
52
53 namespace gmx
54 {
55
56 /********************************************************************
57  * CommandLineParser::Impl
58  */
59
60 /*! \internal \brief
61  * Private implementation class for CommandLineParser.
62  *
63  * \ingroup module_commandline
64  */
65 class CommandLineParser::Impl
66 {
67     public:
68         //! Sets the options object to parse to.
69         explicit Impl(Options *options);
70
71         /*! \brief
72          * Determines whether a cmdline parameter starts an option and the name
73          * of that option.
74          *
75          * \param[in] arg  Individual argument from \c argv.
76          * \returns The beginning of the option name in \p arg, or NULL if
77          *     \p arg does not look like an option.
78          */
79         const char *toOptionName(const char *arg) const;
80
81         //! Helper object for assigning the options.
82         OptionsAssigner         assigner_;
83         //! Whether to allow and skip unknown options.
84         bool                    bSkipUnknown_;
85 };
86
87 CommandLineParser::Impl::Impl(Options *options)
88     : assigner_(options), bSkipUnknown_(false)
89 {
90     assigner_.setAcceptBooleanNoPrefix(true);
91     assigner_.setNoStrictSectioning(true);
92 }
93
94 const char *CommandLineParser::Impl::toOptionName(const char *arg) const
95 {
96     // Lone '-' or '--' is not an option.
97     if (arg[0] != '-' || arg[1] == '\0' || (arg[1] == '-' && arg[2] == '\0'))
98     {
99         return NULL;
100     }
101     // Something starting with '--' is always an option.
102     if (arg[1] == '-')
103     {
104         return arg + 2;
105     }
106     // Don't return numbers as option names.
107     char *endptr;
108     // We are only interested in endptr, not in the actual value.
109     GMX_IGNORE_RETURN_VALUE(std::strtod(arg, &endptr));
110     if (*endptr == '\0')
111     {
112         return NULL;
113     }
114     return arg + 1;
115 }
116
117 /********************************************************************
118  * CommandLineParser
119  */
120
121 CommandLineParser::CommandLineParser(Options *options)
122     : impl_(new Impl(options))
123 {
124 }
125
126 CommandLineParser::~CommandLineParser()
127 {
128 }
129
130 CommandLineParser &CommandLineParser::skipUnknown(bool bEnabled)
131 {
132     impl_->bSkipUnknown_ = bEnabled;
133     return *this;
134 }
135
136 void CommandLineParser::parse(int *argc, char *argv[])
137 {
138     ExceptionInitializer errors("Invalid command-line options");
139     std::string          currentContext;
140     bool                 bInOption = false;
141
142     impl_->assigner_.start();
143     int newi = 1;
144     for (int i = 1; i != *argc; ++i)
145     {
146         const char *const arg        = argv[i];
147         const char *const optionName = impl_->toOptionName(arg);
148         if (optionName != NULL)
149         {
150             if (bInOption)
151             {
152                 try
153                 {
154                     impl_->assigner_.finishOption();
155                 }
156                 catch (UserInputError &ex)
157                 {
158                     ex.prependContext(currentContext);
159                     errors.addCurrentExceptionAsNested();
160                 }
161             }
162             currentContext = "In command-line option " + std::string(arg);
163             try
164             {
165                 bInOption = impl_->assigner_.tryStartOption(optionName);
166                 if (!bInOption)
167                 {
168                     currentContext.clear();
169                     if (!impl_->bSkipUnknown_)
170                     {
171                         std::string message =
172                             "Unknown command-line option " + std::string(arg);
173                         GMX_THROW(InvalidInputError(message));
174                     }
175                 }
176             }
177             catch (UserInputError &ex)
178             {
179                 // If tryStartOption() throws, make sure that the rest gets
180                 // ignored.
181                 // TODO: Consider whether we should remove the option from the
182                 // command line nonetheless, as it is recognized, but just
183                 // invalid.
184                 bInOption = false;
185                 ex.prependContext(currentContext);
186                 errors.addCurrentExceptionAsNested();
187                 currentContext.clear();
188             }
189         }
190         else if (bInOption)
191         {
192             try
193             {
194                 impl_->assigner_.appendValue(arg);
195             }
196             catch (UserInputError &ex)
197             {
198                 ex.prependContext(currentContext);
199                 errors.addCurrentExceptionAsNested();
200             }
201         }
202         // Remove recognized options if applicable.
203         if (!bInOption && impl_->bSkipUnknown_)
204         {
205             argv[newi] = argv[i];
206             ++newi;
207         }
208     }
209     // Update the argc count if argv was modified.
210     if (impl_->bSkipUnknown_)
211     {
212         *argc      = newi;
213         argv[newi] = NULL;
214     }
215     // Finish the last option.
216     if (bInOption)
217     {
218         try
219         {
220             impl_->assigner_.finishOption();
221         }
222         catch (UserInputError &ex)
223         {
224             ex.prependContext(currentContext);
225             errors.addCurrentExceptionAsNested();
226         }
227     }
228     impl_->assigner_.finish();
229     if (errors.hasNestedExceptions())
230     {
231         // TODO: This exception type may not always be appropriate.
232         GMX_THROW(InvalidInputError(errors));
233     }
234 }
235
236 } // namespace gmx