Replace all command line parsing with Options
[alexxy/gromacs.git] / src / gromacs / options / filenameoption.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
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.
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 classes in filenameoption.h and filenameoptionstorage.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_options
41  */
42 #include "filenameoption.h"
43 #include "filenameoptionstorage.h"
44
45 #include <cstring>
46
47 #include <string>
48 #include <vector>
49
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"
56
57 namespace gmx
58 {
59
60 namespace
61 {
62
63 class FileTypeRegistry;
64
65 //! \addtogroup module_options
66 //! \{
67
68 //! Extensions that are recognized as compressed files.
69 const char *const c_compressedExtensions[] =
70 { ".gz", ".Z" };
71
72 //! Shorthand for a list of file extensions.
73 typedef std::vector<const char *> ExtensionList;
74
75 /********************************************************************
76  * FileTypeHandler
77  */
78
79 /*! \internal \brief
80  * Handles a single file type known to FileNameOptionStorage.
81  */
82 class FileTypeHandler
83 {
84     public:
85         //! Returns the list of extensions for this file type.
86         const ExtensionList &extensions() const { return extensions_; }
87
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.
94          *
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.
99          */
100         std::string findFileWithExtension(const std::string &filename) const;
101
102     private:
103         //! Possible extensions for this file type.
104         ExtensionList extensions_;
105
106         /*! \brief
107          * Needed for initialization; all initialization is handled by
108          * FileTypeRegistry.
109          */
110         friend class FileTypeRegistry;
111 };
112
113 bool
114 FileTypeHandler::hasKnownExtension(const std::string &filename) const
115 {
116     for (size_t i = 0; i < extensions_.size(); ++i)
117     {
118         if (endsWith(filename, extensions_[i]))
119         {
120             return true;
121         }
122     }
123     return false;
124 }
125
126 std::string
127 FileTypeHandler::addExtension(const std::string &filename) const
128 {
129     if (extensions_.empty())
130     {
131         return filename;
132     }
133     return filename + extensions_[0];
134 }
135
136 std::string
137 FileTypeHandler::findFileWithExtension(const std::string &filename) const
138 {
139     for (size_t i = 0; i < extensions_.size(); ++i)
140     {
141         std::string testFilename(filename + extensions_[i]);
142         if (File::exists(testFilename))
143         {
144             return testFilename;
145         }
146     }
147     return std::string();
148 }
149
150 /********************************************************************
151  * FileTypeRegistry
152  */
153
154 /*! \internal \brief
155  * Singleton for managing static file type info for FileNameOptionStorage.
156  */
157 class FileTypeRegistry
158 {
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;
165
166     private:
167         //! Initializes the file type registry.
168         FileTypeRegistry();
169
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);
174
175         std::vector<FileTypeHandler> filetypes_;
176 };
177
178 // static
179 const FileTypeRegistry &
180 FileTypeRegistry::instance()
181 {
182     static FileTypeRegistry singleton;
183     return singleton;
184 }
185
186 const FileTypeHandler &
187 FileTypeRegistry::handlerForType(OptionFileType type, int legacyType) const
188 {
189     int index = type;
190     if (type == eftUnknown && legacyType >= 0)
191     {
192         index = eftOptionFileType_NR + legacyType;
193     }
194     GMX_RELEASE_ASSERT(index >= 0 && static_cast<size_t>(index) < filetypes_.size(),
195                        "Invalid file type");
196     return filetypes_[index];
197 }
198
199 FileTypeRegistry::FileTypeRegistry()
200 {
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)
209     {
210         registerType(eftOptionFileType_NR + i, i);
211     }
212 }
213
214 void FileTypeRegistry::registerType(int type, int ftp)
215 {
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)
220     {
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)
225         {
226             filetypes_[type].extensions_.push_back(ftp2ext_with_dot(genericTypes[i]));
227         }
228     }
229     else
230     {
231         registerType(type, ftp2ext_with_dot(ftp));
232     }
233 }
234
235 void FileTypeRegistry::registerType(int type, const char *extension)
236 {
237     GMX_RELEASE_ASSERT(type >= 0 && static_cast<size_t>(type) < filetypes_.size(),
238                        "Invalid file type");
239     filetypes_[type].extensions_.assign(1, extension);
240 }
241
242 /*! \brief
243  * Helper method to complete a file name provided to a file name option.
244  *
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.
252  */
253 std::string completeFileName(const std::string &value, OptionFileType filetype,
254                              int legacyType, bool bCompleteToExisting)
255 {
256     if (bCompleteToExisting && File::exists(value))
257     {
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)
264         {
265             if (endsWith(value, *ext))
266             {
267                 return value.substr(0, value.length() - std::strlen(*ext));
268             }
269         }
270         return value;
271     }
272     const FileTypeRegistry &registry    = FileTypeRegistry::instance();
273     const FileTypeHandler  &typeHandler = registry.handlerForType(filetype, legacyType);
274     if (typeHandler.hasKnownExtension(value))
275     {
276         return value;
277     }
278     if (bCompleteToExisting)
279     {
280         std::string newValue = typeHandler.findFileWithExtension(value);
281         if (!newValue.empty())
282         {
283             return newValue;
284         }
285     }
286     return typeHandler.addExtension(value);
287 }
288
289 //! \}
290
291 }   // namespace
292
293 /********************************************************************
294  * FileNameOptionStorage
295  */
296
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_)
302 {
303     GMX_RELEASE_ASSERT(!hasFlag(efOption_MultipleTimes),
304                        "allowMultiple() is not supported for file name options");
305     if (settings.defaultBasename_ != NULL)
306     {
307         std::string defaultValue =
308             completeFileName(settings.defaultBasename_, filetype_,
309                              legacyType_, false);
310         setDefaultValueIfSet(defaultValue);
311         if (isRequired() || settings.bLegacyOptionalBehavior_)
312         {
313             setDefaultValue(defaultValue);
314         }
315     }
316 }
317
318 void FileNameOptionStorage::setManager(FileNameOptionManager *manager)
319 {
320     GMX_RELEASE_ASSERT(manager_ == NULL || manager_ == manager,
321                        "Manager cannot be changed once set");
322     if (manager_ == NULL)
323     {
324         manager_ = manager;
325     }
326 }
327
328 std::string FileNameOptionStorage::typeString() const
329 {
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)
337     {
338         if (i != extensions.begin())
339         {
340             result.append("/");
341         }
342         result.append(*i);
343     }
344     if (i != extensions.end())
345     {
346         result.append("/...");
347     }
348     if (result.empty())
349     {
350         if (legacyType_ == efRND)
351         {
352             result = "dir";
353         }
354         else
355         {
356             result = "file";
357         }
358     }
359     return result;
360 }
361
362 std::string FileNameOptionStorage::formatExtraDescription() const
363 {
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)
369     {
370         result.append(":");
371         ExtensionList::const_iterator i;
372         for (i = extensions.begin(); i != extensions.end(); ++i)
373         {
374             result.append(" ");
375             result.append((*i) + 1);
376         }
377     }
378     return result;
379 }
380
381 std::string FileNameOptionStorage::formatSingleValue(const std::string &value) const
382 {
383     return value;
384 }
385
386 void FileNameOptionStorage::convertValue(const std::string &value)
387 {
388     bool bInput = isInputFile() || isInputOutputFile();
389     addValue(completeFileName(value, filetype_, legacyType_, bInput));
390 }
391
392 void FileNameOptionStorage::processAll()
393 {
394     if (hasFlag(efOption_HasDefaultValue))
395     {
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))
406         {
407             std::string oldValue = valueList[0];
408             std::string newValue = stripSuffixIfPresent(oldValue, extensions[0]);
409             if (bGlobalDefault)
410             {
411                 newValue = manager_->defaultFileName();
412             }
413             newValue = completeFileName(newValue, filetype_, legacyType_, bInput);
414             if (newValue != oldValue)
415             {
416                 valueList[0] = newValue;
417                 refreshValues();
418             }
419         }
420     }
421 }
422
423 bool FileNameOptionStorage::isDirectoryOption() const
424 {
425     return legacyType_ == efRND;
426 }
427
428 ConstArrayRef<const char *> FileNameOptionStorage::extensions() const
429 {
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());
434 }
435
436 /********************************************************************
437  * FileNameOptionInfo
438  */
439
440 FileNameOptionInfo::FileNameOptionInfo(FileNameOptionStorage *option)
441     : OptionInfo(option)
442 {
443 }
444
445 FileNameOptionStorage &FileNameOptionInfo::option()
446 {
447     return static_cast<FileNameOptionStorage &>(OptionInfo::option());
448 }
449
450 const FileNameOptionStorage &FileNameOptionInfo::option() const
451 {
452     return static_cast<const FileNameOptionStorage &>(OptionInfo::option());
453 }
454
455 void FileNameOptionInfo::setManager(FileNameOptionManager *manager)
456 {
457     option().setManager(manager);
458 }
459
460 bool FileNameOptionInfo::isInputFile() const
461 {
462     return option().isInputFile();
463 }
464
465 bool FileNameOptionInfo::isOutputFile() const
466 {
467     return option().isOutputFile();
468 }
469
470 bool FileNameOptionInfo::isInputOutputFile() const
471 {
472     return option().isInputOutputFile();
473 }
474
475 bool FileNameOptionInfo::isLibraryFile() const
476 {
477     return option().isLibraryFile();
478 }
479
480 bool FileNameOptionInfo::isDirectoryOption() const
481 {
482     return option().isDirectoryOption();
483 }
484
485 FileNameOptionInfo::ExtensionList FileNameOptionInfo::extensions() const
486 {
487     return option().extensions();
488 }
489
490 /********************************************************************
491  * FileNameOption
492  */
493
494 AbstractOptionStoragePointer FileNameOption::createStorage() const
495 {
496     return AbstractOptionStoragePointer(new FileNameOptionStorage(*this));
497 }
498
499 } // namespace gmx