d6aa17140d65db27cd77cd0f31ef291dd0a6903a
[alexxy/gromacs.git] / src / gromacs / utility / path.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2011,2012,2013,2014,2015, 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 functions in path.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_utility
41  */
42 #include "gmxpre.h"
43
44 #include "path.h"
45
46 #include "config.h"
47
48 #include <cctype>
49 #include <cerrno>
50 #include <cstdlib>
51 #include <cstring>
52
53 #include <algorithm>
54
55 #include <sys/stat.h>
56
57 #ifdef GMX_NATIVE_WINDOWS
58 #include <Windows.h>
59 #include <direct.h>
60 #else
61 #ifdef HAVE_UNISTD_H
62 #include <unistd.h>
63 #endif
64 #endif
65
66 #include "gromacs/utility/dir_separator.h"
67 #include "gromacs/utility/exceptions.h"
68 #include "gromacs/utility/futil.h"
69 #include "gromacs/utility/stringutil.h"
70
71 namespace
72 {
73
74 //! Directory separator to use when joining paths.
75 const char cDirSeparator = '/';
76 //! Directory separators to use when parsing paths.
77 const char cDirSeparators[] = "/\\";
78 /*! \var cPathSeparator
79  * \brief
80  * Separator to use to split the PATH environment variable.
81  *
82  * When reading the PATH environment variable, Unix separates entries
83  * with colon, while windows uses semicolon.
84  */
85 #ifdef GMX_NATIVE_WINDOWS
86 const char cPathSeparator = ';';
87 #else
88 const char cPathSeparator = ':';
89 #endif
90
91 //! Check whether a given character is a directory separator.
92 bool isDirSeparator(char chr)
93 {
94     return std::strchr(cDirSeparators, chr);
95 }
96
97 } // namespace
98
99 namespace gmx
100 {
101
102 /********************************************************************
103  * Path
104  */
105
106 bool Path::containsDirectory(const std::string &path)
107 {
108     return path.find_first_of(cDirSeparators) != std::string::npos;
109 }
110
111 /* Check if the program name begins with "/" on unix/cygwin, or
112  * with "\" or "X:\" on windows. If not, the program name
113  * is relative to the current directory.
114  */
115 bool Path::isAbsolute(const char *path)
116 {
117     if (isDirSeparator(path[0]))
118     {
119         return true;
120     }
121 #ifdef GMX_NATIVE_WINDOWS
122     return path[0] != '\0' && path[1] == ':' && isDirSeparator(path[2]);
123 #else
124     return false;
125 #endif
126 }
127
128 bool Path::isAbsolute(const std::string &path)
129 {
130     return isAbsolute(path.c_str());
131 }
132
133 #ifdef GMX_NATIVE_WINDOWS
134 namespace
135 {
136 struct handle_wrapper
137 {
138     HANDLE handle;
139     handle_wrapper(HANDLE h)
140         : handle(h){}
141     ~handle_wrapper()
142     {
143         if (handle != INVALID_HANDLE_VALUE)
144         {
145             ::CloseHandle(handle);
146         }
147     }
148 };
149 }
150 #endif
151
152 bool Path::isEquivalent(const std::string &path1, const std::string &path2)
153 {
154     //based on boost_1_56_0/libs/filesystem/src/operations.cpp under BSL
155 #ifdef GMX_NATIVE_WINDOWS
156     // Note well: Physical location on external media is part of the
157     // equivalence criteria. If there are no open handles, physical location
158     // can change due to defragmentation or other relocations. Thus handles
159     // must be held open until location information for both paths has
160     // been retrieved.
161
162     // p2 is done first, so any error reported is for p1
163     // FixME: #1635
164     handle_wrapper h2(
165             CreateFile(
166                     path2.c_str(),
167                     0,
168                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
169                     0,
170                     OPEN_EXISTING,
171                     FILE_FLAG_BACKUP_SEMANTICS,
172                     0));
173
174     handle_wrapper h1(
175             CreateFile(
176                     path1.c_str(),
177                     0,
178                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
179                     0,
180                     OPEN_EXISTING,
181                     FILE_FLAG_BACKUP_SEMANTICS,
182                     0));
183
184     if (h1.handle == INVALID_HANDLE_VALUE
185         || h2.handle == INVALID_HANDLE_VALUE)
186     {
187         // if one is invalid and the other isn't, then they aren't equivalent,
188         // but if both are invalid then it is an error
189         if (h1.handle == INVALID_HANDLE_VALUE
190             && h2.handle == INVALID_HANDLE_VALUE)
191         {
192             GMX_THROW(FileIOError("Path::isEquivalent called with two invalid files"));
193         }
194
195         return false;
196     }
197
198     // at this point, both handles are known to be valid
199
200     BY_HANDLE_FILE_INFORMATION info1, info2;
201
202     if (!GetFileInformationByHandle(h1.handle, &info1))
203     {
204         GMX_THROW(FileIOError("Path::isEquivalent: GetFileInformationByHandle failed"));
205     }
206
207     if (!GetFileInformationByHandle(h2.handle, &info2))
208     {
209         GMX_THROW(FileIOError("Path::isEquivalent: GetFileInformationByHandle failed"));
210     }
211
212     // In theory, volume serial numbers are sufficient to distinguish between
213     // devices, but in practice VSN's are sometimes duplicated, so last write
214     // time and file size are also checked.
215     return
216         info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
217         && info1.nFileIndexHigh == info2.nFileIndexHigh
218         && info1.nFileIndexLow == info2.nFileIndexLow
219         && info1.nFileSizeHigh == info2.nFileSizeHigh
220         && info1.nFileSizeLow == info2.nFileSizeLow
221         && info1.ftLastWriteTime.dwLowDateTime
222         == info2.ftLastWriteTime.dwLowDateTime
223         && info1.ftLastWriteTime.dwHighDateTime
224         == info2.ftLastWriteTime.dwHighDateTime;
225 #else
226     struct stat s1, s2;
227     int         e2 = stat(path2.c_str(), &s2);
228     int         e1 = stat(path1.c_str(), &s1);
229
230     if (e1 != 0 || e2 != 0)
231     {
232         // if one is invalid and the other isn't then they aren't equivalent,
233         // but if both are invalid then it is an error.
234         if (e1 != 0 && e2 != 0)
235         {
236             GMX_THROW_WITH_ERRNO(
237                     FileIOError("Path::isEquivalent called with two invalid files"),
238                     "stat", errno);
239         }
240         return false;
241     }
242
243     // both stats now known to be valid
244     return s1.st_dev == s2.st_dev && s1.st_ino == s2.st_ino
245            // According to the POSIX stat specs, "The st_ino and st_dev fields
246            // taken together uniquely identify the file within the system."
247            // Just to be sure, size and mod time are also checked.
248            && s1.st_size == s2.st_size && s1.st_mtime == s2.st_mtime;
249 #endif
250 }
251
252 std::string Path::join(const std::string &path1,
253                        const std::string &path2)
254 {
255     // TODO: Remove extra separators if they are present in the input paths.
256     return path1 + cDirSeparator + path2;
257 }
258
259
260 std::string Path::join(const std::string &path1,
261                        const std::string &path2,
262                        const std::string &path3)
263 {
264     // TODO: Remove extra separators if they are present in the input paths.
265     return path1 + cDirSeparator + path2 + cDirSeparator + path3;
266 }
267
268 std::string Path::getParentPath(const std::string &path)
269 {
270     /* Expects that the path doesn't contain "." or "..". If used on a path for
271      * which this isn't guaranteed realpath needs to be called first. */
272     size_t pos = path.find_last_of(cDirSeparators);
273     if (pos == std::string::npos)
274     {
275         return std::string();
276     }
277     return path.substr(0, pos);
278 }
279
280 std::string Path::getFilename(const std::string &path)
281 {
282     size_t pos = path.find_last_of(cDirSeparators);
283     if (pos == std::string::npos)
284     {
285         return path;
286     }
287     return path.substr(pos+1);
288 }
289
290 bool Path::hasExtension(const std::string &path)
291 {
292     return getFilename(path).find('.') != std::string::npos;
293 }
294
295 std::string Path::stripExtension(const std::string &path)
296 {
297     size_t dirSeparatorPos = path.find_last_of(cDirSeparators);
298     size_t extPos          = path.find_last_of('.');
299     if (extPos == std::string::npos
300         || (dirSeparatorPos != std::string::npos && extPos < dirSeparatorPos))
301     {
302         return path;
303     }
304     return path.substr(0, extPos);
305 }
306
307 std::string Path::normalize(const std::string &path)
308 {
309     std::string result(path);
310     if (DIR_SEPARATOR != '/')
311     {
312         std::replace(result.begin(), result.end(), '/', DIR_SEPARATOR);
313     }
314     return result;
315 }
316
317 bool Path::exists(const char *path)
318 {
319     return gmx_fexist(path);
320 }
321
322 bool Path::exists(const std::string &path)
323 {
324     return exists(path.c_str());
325 }
326
327 std::string Path::getWorkingDirectory()
328 {
329     // TODO: Use exceptions instead of gmx_fatal().
330     char cwd[GMX_PATH_MAX];
331     gmx_getcwd(cwd, sizeof(cwd));
332     return cwd;
333 }
334
335 void Path::splitPathEnvironment(const std::string        &pathEnv,
336                                 std::vector<std::string> *result)
337 {
338     size_t prevPos = 0;
339     size_t separator;
340     do
341     {
342         separator = pathEnv.find(cPathSeparator, prevPos);
343         result->push_back(pathEnv.substr(prevPos, separator - prevPos));
344         prevPos = separator + 1;
345     }
346     while (separator != std::string::npos);
347 }
348
349 std::vector<std::string> Path::getExecutablePaths()
350 {
351     std::vector<std::string> result;
352 #ifdef GMX_NATIVE_WINDOWS
353     // Add the local dir since it is not in the path on Windows.
354     result.push_back("");
355 #endif
356     const char *path = std::getenv("PATH");
357     if (path != NULL)
358     {
359         splitPathEnvironment(path, &result);
360     }
361     return result;
362 }
363
364 std::string Path::resolveSymlinks(const std::string &path)
365 {
366     /* Does not fully resolve the path like realpath/boost::canonical would.
367      * It doesn't resolve path elements (including "." or ".."), but only
368      * resolves the entire path (it does that recursively). */
369     std::string result(path);
370 #ifndef GMX_NATIVE_WINDOWS
371     char        buf[GMX_PATH_MAX];
372     int         length;
373     while ((length = readlink(result.c_str(), buf, sizeof(buf)-1)) > 0)
374     {
375         buf[length] = '\0';
376         if (isAbsolute(buf))
377         {
378             result = buf;
379         }
380         else
381         {
382             result = join(getParentPath(result), buf);
383         }
384     }
385 #endif
386     return result;
387 }
388
389
390 /********************************************************************
391  * Directory
392  */
393
394 int Directory::create(const char *path)
395 {
396     if (Directory::exists(path))
397     {
398         return 0;
399     }
400 #ifdef GMX_NATIVE_WINDOWS
401     if (_mkdir(path))
402 #else
403     if (mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IWOTH) != 0)
404 #endif
405     {
406         // TODO: Proper error handling.
407         return -1;
408     }
409     return 0;
410 }
411
412
413 int Directory::create(const std::string &path)
414 {
415     return create(path.c_str());
416 }
417
418
419 bool Directory::exists(const char *path)
420 {
421     struct stat info;
422     if (stat(path, &info) != 0)
423     {
424         if (errno != ENOENT && errno != ENOTDIR)
425         {
426             // TODO: Proper error handling.
427         }
428         return false;
429     }
430 #ifdef GMX_NATIVE_WINDOWS
431     return ((_S_IFDIR & info.st_mode) != 0);
432 #else
433     return S_ISDIR(info.st_mode);
434 #endif
435 }
436
437
438 bool Directory::exists(const std::string &path)
439 {
440     return exists(path.c_str());
441 }
442
443 } // namespace gmx