Apply clang-format-11
[alexxy/gromacs.git] / src / gromacs / utility / directoryenumerator.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010,2011,2014,2015,2016 by the GROMACS development team.
5  * Copyright (c) 2017,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.
9  *
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.
14  *
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.
19  *
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.
24  *
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.
32  *
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.
35  */
36 /*! \internal \file
37  * \brief
38  * Implements gmx::DirectoryEnumerator.
39  *
40  * \author Erik Lindahl (original C implementation)
41  * \author Teemu Murtola <teemu.murtola@gmail.com> (C++ wrapper + errno handling)
42  * \ingroup module_utility
43  */
44 #include "gmxpre.h"
45
46 #include "directoryenumerator.h"
47
48 #include "config.h"
49
50 #include <cerrno>
51 #include <cstdio>
52
53 #include <algorithm>
54 #include <string>
55 #include <vector>
56
57 #if HAVE_DIRENT_H
58 #    include <dirent.h>
59 #endif
60 #if GMX_NATIVE_WINDOWS
61 #    include <io.h>
62 #endif
63
64 #include "gromacs/utility/exceptions.h"
65 #include "gromacs/utility/fatalerror.h"
66 #include "gromacs/utility/futil.h"
67 #include "gromacs/utility/gmxassert.h"
68 #include "gromacs/utility/smalloc.h"
69 #include "gromacs/utility/stringutil.h"
70
71 namespace gmx
72 {
73
74 /********************************************************************
75  * DirectoryEnumerator::Impl
76  */
77
78 // TODO: Consider whether checking the return value of closing would be useful,
79 // and what could we do if it fails?
80 #if GMX_NATIVE_WINDOWS
81 // TODO: Consider if Windows provides more error details through other APIs.
82 class DirectoryEnumerator::Impl
83 {
84 public:
85     static Impl* init(const char* dirname, bool bThrow)
86     {
87         std::string tmpname(dirname);
88         // Remove possible trailing directory separator.
89         // TODO: Use a method in gmx::Path instead.
90         if (tmpname.back() == '/' || tmpname.back() == '\\')
91         {
92             tmpname.pop_back();
93         }
94
95         // Add wildcard.
96         tmpname.append("/*");
97
98         errno = 0;
99         _finddata_t finddata;
100         intptr_t    handle = _findfirst(tmpname.c_str(), &finddata);
101         if (handle < 0L)
102         {
103             if (errno != ENOENT && bThrow)
104             {
105                 const int         code = errno;
106                 const std::string message =
107                         formatString("Failed to list files in directory '%s'", dirname);
108                 GMX_THROW_WITH_ERRNO(FileIOError(message), "_findfirst", code);
109             }
110             return NULL;
111         }
112         return new Impl(handle, finddata);
113     }
114     Impl(intptr_t handle, _finddata_t finddata) :
115         windows_handle(handle), finddata(finddata), bFirst_(true)
116     {
117     }
118     ~Impl() { _findclose(windows_handle); }
119
120     bool nextFile(std::string* filename)
121     {
122         if (bFirst_)
123         {
124             *filename = finddata.name;
125             bFirst_   = false;
126             return true;
127         }
128         else
129         {
130             errno = 0;
131             if (_findnext(windows_handle, &finddata) != 0)
132             {
133                 if (errno == 0 || errno == ENOENT)
134                 {
135                     filename->clear();
136                     return false;
137                 }
138                 else
139                 {
140                     GMX_THROW_WITH_ERRNO(
141                             FileIOError("Failed to list files in a directory"), "_findnext", errno);
142                 }
143             }
144             *filename = finddata.name;
145             return true;
146         }
147     }
148
149 private:
150     intptr_t    windows_handle;
151     _finddata_t finddata;
152     bool        bFirst_;
153 };
154 #elif HAVE_DIRENT_H
155 class DirectoryEnumerator::Impl
156 {
157 public:
158     static Impl* init(const char* dirname, bool bThrow)
159     {
160         errno       = 0;
161         DIR* handle = opendir(dirname);
162         if (handle == nullptr)
163         {
164             if (bThrow)
165             {
166                 const int         code = errno;
167                 const std::string message =
168                         formatString("Failed to list files in directory '%s'", dirname);
169                 GMX_THROW_WITH_ERRNO(FileIOError(message), "opendir", code);
170             }
171             return nullptr;
172         }
173         return new Impl(handle);
174     }
175     explicit Impl(DIR* handle) : dirent_handle(handle) {}
176     ~Impl() { closedir(dirent_handle); }
177
178     bool nextFile(std::string* filename)
179     {
180         errno     = 0;
181         dirent* p = readdir(dirent_handle);
182         if (p == nullptr)
183         {
184             if (errno == 0)
185             {
186                 // All the files have been found.
187                 filename->clear();
188                 return false;
189             }
190             else
191             {
192                 GMX_THROW_WITH_ERRNO(FileIOError("Failed to list files in a directory"), "readdir", errno);
193             }
194         }
195         *filename = p->d_name;
196         return true;
197     }
198
199 private:
200     DIR* dirent_handle;
201 };
202 #else
203 class DirectoryEnumerator::Impl
204 {
205 public:
206     static Impl* init(const char* /*dirname*/, bool /*bThrow*/)
207     {
208         std::string message(
209                 "Source compiled without POSIX dirent or Windows support "
210                 "- cannot scan directories. In the very unlikely event "
211                 "this is not a compile-time mistake you could consider "
212                 "implementing support for your platform in "
213                 "directoryenumerator.cpp, but contact the developers "
214                 "to make sure it's really necessary!");
215         GMX_THROW(NotImplementedError(message));
216     }
217
218     bool nextFile(std::string* /*filename*/) { return false; }
219 };
220 #endif
221
222 /********************************************************************
223  * DirectoryEnumerator
224  */
225
226 // static
227 std::vector<std::string> DirectoryEnumerator::enumerateFilesWithExtension(const char* dirname,
228                                                                           const char* extension,
229                                                                           bool        bThrow)
230 {
231     std::vector<std::string> result;
232     DirectoryEnumerator      dir(dirname, bThrow);
233     std::string              nextName;
234     while (dir.nextFile(&nextName))
235     {
236         if (debug)
237         {
238             std::fprintf(debug, "dir '%s' file '%s'\n", dirname, nextName.c_str());
239         }
240         // TODO: What about case sensitivity?
241         if (endsWith(nextName, extension))
242         {
243             result.push_back(nextName);
244         }
245     }
246
247     std::sort(result.begin(), result.end());
248     return result;
249 }
250
251
252 DirectoryEnumerator::DirectoryEnumerator(const char* dirname, bool bThrow) : impl_(nullptr)
253 {
254     GMX_RELEASE_ASSERT(dirname != nullptr && dirname[0] != '\0',
255                        "Attempted to open empty/null directory path");
256     impl_.reset(Impl::init(dirname, bThrow));
257 }
258
259 DirectoryEnumerator::DirectoryEnumerator(const std::string& dirname, bool bThrow) : impl_(nullptr)
260 {
261     GMX_RELEASE_ASSERT(!dirname.empty(), "Attempted to open empty/null directory path");
262     impl_.reset(Impl::init(dirname.c_str(), bThrow));
263 }
264
265 DirectoryEnumerator::~DirectoryEnumerator() {}
266
267 bool DirectoryEnumerator::nextFile(std::string* filename)
268 {
269     if (impl_ == nullptr)
270     {
271         filename->clear();
272         return false;
273     }
274     return impl_->nextFile(filename);
275 }
276
277 } // namespace gmx