Replace all command line parsing with Options
[gromacs.git] / src / gromacs / options / filenameoption.cpp
blob9922e16fa977b6a2b3fc27bb7961745ac3324ee9
1 /*
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.
35 /*! \internal \file
36 * \brief
37 * Implements classes in filenameoption.h and filenameoptionstorage.h.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_options
42 #include "filenameoption.h"
43 #include "filenameoptionstorage.h"
45 #include <cstring>
47 #include <string>
48 #include <vector>
50 #include "gromacs/fileio/filenm.h"
51 #include "gromacs/options/filenameoptionmanager.h"
52 #include "gromacs/utility/arrayref.h"
53 #include "gromacs/utility/file.h"
54 #include "gromacs/utility/gmxassert.h"
55 #include "gromacs/utility/stringutil.h"
57 namespace gmx
60 namespace
63 class FileTypeRegistry;
65 //! \addtogroup module_options
66 //! \{
68 //! Extensions that are recognized as compressed files.
69 const char *const c_compressedExtensions[] =
70 { ".gz", ".Z" };
72 //! Shorthand for a list of file extensions.
73 typedef std::vector<const char *> ExtensionList;
75 /********************************************************************
76 * FileTypeHandler
79 /*! \internal \brief
80 * Handles a single file type known to FileNameOptionStorage.
82 class FileTypeHandler
84 public:
85 //! Returns the list of extensions for this file type.
86 const ExtensionList &extensions() const { return extensions_; }
88 //! Returns whether \p filename has a valid extension for this type.
89 bool hasKnownExtension(const std::string &filename) const;
90 //! Adds a default extension for this type to \p filename.
91 std::string addExtension(const std::string &filename) const;
92 /*! \brief
93 * Adds an extension to \p filename if it results in an existing file.
95 * Tries to add each extension for this file type to \p filename and
96 * checks whether this results in an existing file.
97 * The first match is returned.
98 * Returns an empty string if no existing file is found.
100 std::string findFileWithExtension(const std::string &filename) const;
102 private:
103 //! Possible extensions for this file type.
104 ExtensionList extensions_;
106 /*! \brief
107 * Needed for initialization; all initialization is handled by
108 * FileTypeRegistry.
110 friend class FileTypeRegistry;
113 bool
114 FileTypeHandler::hasKnownExtension(const std::string &filename) const
116 for (size_t i = 0; i < extensions_.size(); ++i)
118 if (endsWith(filename, extensions_[i]))
120 return true;
123 return false;
126 std::string
127 FileTypeHandler::addExtension(const std::string &filename) const
129 if (extensions_.empty())
131 return filename;
133 return filename + extensions_[0];
136 std::string
137 FileTypeHandler::findFileWithExtension(const std::string &filename) const
139 for (size_t i = 0; i < extensions_.size(); ++i)
141 std::string testFilename(filename + extensions_[i]);
142 if (File::exists(testFilename))
144 return testFilename;
147 return std::string();
150 /********************************************************************
151 * FileTypeRegistry
154 /*! \internal \brief
155 * Singleton for managing static file type info for FileNameOptionStorage.
157 class FileTypeRegistry
159 public:
160 //! Returns a singleton instance of this class.
161 static const FileTypeRegistry &instance();
162 //! Returns a handler for a single file type.
163 const FileTypeHandler &
164 handlerForType(OptionFileType type, int legacyType) const;
166 private:
167 //! Initializes the file type registry.
168 FileTypeRegistry();
170 //! Registers a file type that corresponds to a ftp in filenm.h.
171 void registerType(int type, int ftp);
172 //! Registers a file type with a single extension.
173 void registerType(int type, const char *extension);
175 std::vector<FileTypeHandler> filetypes_;
178 // static
179 const FileTypeRegistry &
180 FileTypeRegistry::instance()
182 static FileTypeRegistry singleton;
183 return singleton;
186 const FileTypeHandler &
187 FileTypeRegistry::handlerForType(OptionFileType type, int legacyType) const
189 int index = type;
190 if (type == eftUnknown && legacyType >= 0)
192 index = eftOptionFileType_NR + legacyType;
194 GMX_RELEASE_ASSERT(index >= 0 && static_cast<size_t>(index) < filetypes_.size(),
195 "Invalid file type");
196 return filetypes_[index];
199 FileTypeRegistry::FileTypeRegistry()
201 filetypes_.resize(eftOptionFileType_NR + efNR);
202 registerType(eftTopology, efTPS);
203 registerType(eftTrajectory, efTRX);
204 registerType(eftPDB, efPDB);
205 registerType(eftIndex, efNDX);
206 registerType(eftPlot, efXVG);
207 registerType(eftGenericData, efDAT);
208 for (int i = 0; i < efNR; ++i)
210 registerType(eftOptionFileType_NR + i, i);
214 void FileTypeRegistry::registerType(int type, int ftp)
216 GMX_RELEASE_ASSERT(type >= 0 && static_cast<size_t>(type) < filetypes_.size(),
217 "Invalid file type");
218 const int genericTypeCount = ftp2generic_count(ftp);
219 if (genericTypeCount > 0)
221 const int *const genericTypes = ftp2generic_list(ftp);
222 filetypes_[type].extensions_.clear();
223 filetypes_[type].extensions_.reserve(genericTypeCount);
224 for (int i = 0; i < genericTypeCount; ++i)
226 filetypes_[type].extensions_.push_back(ftp2ext_with_dot(genericTypes[i]));
229 else
231 registerType(type, ftp2ext_with_dot(ftp));
235 void FileTypeRegistry::registerType(int type, const char *extension)
237 GMX_RELEASE_ASSERT(type >= 0 && static_cast<size_t>(type) < filetypes_.size(),
238 "Invalid file type");
239 filetypes_[type].extensions_.assign(1, extension);
242 /*! \brief
243 * Helper method to complete a file name provided to a file name option.
245 * \param[in] value Value provided to the file name option.
246 * \param[in] filetype File type for the option.
247 * \param[in] legacyType If \p filetype is eftUnknown, this gives the type as
248 * an enum value from filenm.h.
249 * \param[in] bCompleteToExisting
250 * Whether to check existing files when completing the extension.
251 * \returns \p value with possible extension added.
253 std::string completeFileName(const std::string &value, OptionFileType filetype,
254 int legacyType, bool bCompleteToExisting)
256 if (bCompleteToExisting && File::exists(value))
258 // TODO: This may not work as expected if the value is passed to a
259 // function that uses fn2ftp() to determine the file type and the input
260 // file has an unrecognized extension.
261 ConstArrayRef<const char *> compressedExtensions(c_compressedExtensions);
262 ConstArrayRef<const char *>::const_iterator ext;
263 for (ext = compressedExtensions.begin(); ext != compressedExtensions.end(); ++ext)
265 if (endsWith(value, *ext))
267 return value.substr(0, value.length() - std::strlen(*ext));
270 return value;
272 const FileTypeRegistry &registry = FileTypeRegistry::instance();
273 const FileTypeHandler &typeHandler = registry.handlerForType(filetype, legacyType);
274 if (typeHandler.hasKnownExtension(value))
276 return value;
278 if (bCompleteToExisting)
280 std::string newValue = typeHandler.findFileWithExtension(value);
281 if (!newValue.empty())
283 return newValue;
286 return typeHandler.addExtension(value);
289 //! \}
291 } // namespace
293 /********************************************************************
294 * FileNameOptionStorage
297 FileNameOptionStorage::FileNameOptionStorage(const FileNameOption &settings)
298 : MyBase(settings), info_(this), manager_(NULL),
299 filetype_(settings.filetype_), legacyType_(settings.legacyType_),
300 bRead_(settings.bRead_), bWrite_(settings.bWrite_),
301 bLibrary_(settings.bLibrary_)
303 GMX_RELEASE_ASSERT(!hasFlag(efOption_MultipleTimes),
304 "allowMultiple() is not supported for file name options");
305 if (settings.defaultBasename_ != NULL)
307 std::string defaultValue =
308 completeFileName(settings.defaultBasename_, filetype_,
309 legacyType_, false);
310 setDefaultValueIfSet(defaultValue);
311 if (isRequired() || settings.bLegacyOptionalBehavior_)
313 setDefaultValue(defaultValue);
318 void FileNameOptionStorage::setManager(FileNameOptionManager *manager)
320 GMX_RELEASE_ASSERT(manager_ == NULL || manager_ == manager,
321 "Manager cannot be changed once set");
322 if (manager_ == NULL)
324 manager_ = manager;
328 std::string FileNameOptionStorage::typeString() const
330 const FileTypeRegistry &registry = FileTypeRegistry::instance();
331 const FileTypeHandler &typeHandler = registry.handlerForType(filetype_, legacyType_);
332 const ExtensionList &extensions = typeHandler.extensions();
333 std::string result;
334 ExtensionList::const_iterator i;
335 int count = 0;
336 for (i = extensions.begin(); count < 2 && i != extensions.end(); ++i, ++count)
338 if (i != extensions.begin())
340 result.append("/");
342 result.append(*i);
344 if (i != extensions.end())
346 result.append("/...");
348 if (result.empty())
350 if (legacyType_ == efRND)
352 result = "dir";
354 else
356 result = "file";
359 return result;
362 std::string FileNameOptionStorage::formatExtraDescription() const
364 const FileTypeRegistry &registry = FileTypeRegistry::instance();
365 const FileTypeHandler &typeHandler = registry.handlerForType(filetype_, legacyType_);
366 const ExtensionList &extensions = typeHandler.extensions();
367 std::string result;
368 if (extensions.size() > 2)
370 result.append(":");
371 ExtensionList::const_iterator i;
372 for (i = extensions.begin(); i != extensions.end(); ++i)
374 result.append(" ");
375 result.append((*i) + 1);
378 return result;
381 std::string FileNameOptionStorage::formatSingleValue(const std::string &value) const
383 return value;
386 void FileNameOptionStorage::convertValue(const std::string &value)
388 bool bInput = isInputFile() || isInputOutputFile();
389 addValue(completeFileName(value, filetype_, legacyType_, bInput));
392 void FileNameOptionStorage::processAll()
394 if (hasFlag(efOption_HasDefaultValue))
396 const bool bInput = isInputFile() || isInputOutputFile();
397 const FileTypeRegistry &registry = FileTypeRegistry::instance();
398 const FileTypeHandler &typeHandler = registry.handlerForType(filetype_, legacyType_);
399 const ExtensionList &extensions = typeHandler.extensions();
400 ValueList &valueList = values();
401 GMX_RELEASE_ASSERT(valueList.size() == 1,
402 "There should be only one default value");
403 const bool bGlobalDefault =
404 (manager_ != NULL && !manager_->defaultFileName().empty());
405 if (!valueList[0].empty() && (extensions.size() > 1 || bGlobalDefault))
407 std::string oldValue = valueList[0];
408 std::string newValue = stripSuffixIfPresent(oldValue, extensions[0]);
409 if (bGlobalDefault)
411 newValue = manager_->defaultFileName();
413 newValue = completeFileName(newValue, filetype_, legacyType_, bInput);
414 if (newValue != oldValue)
416 valueList[0] = newValue;
417 refreshValues();
423 bool FileNameOptionStorage::isDirectoryOption() const
425 return legacyType_ == efRND;
428 ConstArrayRef<const char *> FileNameOptionStorage::extensions() const
430 const FileTypeRegistry &registry = FileTypeRegistry::instance();
431 const FileTypeHandler &typeHandler = registry.handlerForType(filetype_, legacyType_);
432 const ExtensionList &extensions = typeHandler.extensions();
433 return ConstArrayRef<const char *>(extensions.begin(), extensions.end());
436 /********************************************************************
437 * FileNameOptionInfo
440 FileNameOptionInfo::FileNameOptionInfo(FileNameOptionStorage *option)
441 : OptionInfo(option)
445 FileNameOptionStorage &FileNameOptionInfo::option()
447 return static_cast<FileNameOptionStorage &>(OptionInfo::option());
450 const FileNameOptionStorage &FileNameOptionInfo::option() const
452 return static_cast<const FileNameOptionStorage &>(OptionInfo::option());
455 void FileNameOptionInfo::setManager(FileNameOptionManager *manager)
457 option().setManager(manager);
460 bool FileNameOptionInfo::isInputFile() const
462 return option().isInputFile();
465 bool FileNameOptionInfo::isOutputFile() const
467 return option().isOutputFile();
470 bool FileNameOptionInfo::isInputOutputFile() const
472 return option().isInputOutputFile();
475 bool FileNameOptionInfo::isLibraryFile() const
477 return option().isLibraryFile();
480 bool FileNameOptionInfo::isDirectoryOption() const
482 return option().isDirectoryOption();
485 FileNameOptionInfo::ExtensionList FileNameOptionInfo::extensions() const
487 return option().extensions();
490 /********************************************************************
491 * FileNameOption
494 AbstractOptionStoragePointer FileNameOption::createStorage() const
496 return AbstractOptionStoragePointer(new FileNameOptionStorage(*this));
499 } // namespace gmx