Merge release-4-6 into master
[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, 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 "gromacs/utility/path.h"
43
44 #include <cctype>
45 #include <cerrno>
46 #include <cstdlib>
47 #include <cstring>
48
49 #include <algorithm>
50
51 #include "config.h"
52
53 #include <sys/stat.h>
54 #ifdef GMX_NATIVE_WINDOWS
55 #include <direct.h>
56 #else
57 #ifdef HAVE_UNISTD_H
58 #include <unistd.h>
59 #endif
60 #endif
61
62 #include "gromacs/fileio/futil.h"
63 #include "gromacs/utility/stringutil.h"
64
65 namespace
66 {
67
68 //! \addtogroup module_utility
69 //! \{
70
71 //! Directory separator to use when joining paths.
72 const char cDirSeparator = '/';
73 //! Directory separators to use when parsing paths.
74 const char cDirSeparators[] = "/\\";
75 /*! \var cPathSeparator
76  * \brief
77  * Separator to use to split the PATH environment variable.
78  *
79  * When reading the PATH environment variable, Unix separates entries
80  * with colon, while windows uses semicolon.
81  */
82 #ifdef GMX_NATIVE_WINDOWS
83 const char cPathSeparator = ';';
84 #else
85 const char cPathSeparator = ':';
86 #endif
87
88 //! Check whether a given character is a directory separator.
89 bool isDirSeparator(char chr)
90 {
91     return std::strchr(cDirSeparators, chr);
92 }
93
94 //! \}
95
96 } // namespace
97
98 namespace gmx
99 {
100
101 /********************************************************************
102  * Path
103  */
104
105 bool Path::containsDirectory(const std::string &path)
106 {
107     return path.find_first_of(cDirSeparators) != std::string::npos;
108 }
109
110 /* Check if the program name begins with "/" on unix/cygwin, or
111  * with "\" or "X:\" on windows. If not, the program name
112  * is relative to the current directory.
113  */
114 bool Path::isAbsolute(const char *path)
115 {
116     if (isDirSeparator(path[0]))
117     {
118         return true;
119     }
120 #ifdef GMX_NATIVE_WINDOWS
121     return path[0] != '\0' && path[1] == ':' && isDirSeparator(path[2]);
122 #else
123     return false;
124 #endif
125 }
126
127 bool Path::isAbsolute(const std::string &path)
128 {
129     return isAbsolute(path.c_str());
130 }
131
132 bool Path::startsWith(const std::string &path, const std::string &prefix)
133 {
134     return gmx::startsWith(normalize(path), normalize(prefix));
135 }
136
137 std::string Path::join(const std::string &path1,
138                        const std::string &path2)
139 {
140     // TODO: Remove extra separators if they are present in the input paths.
141     return path1 + cDirSeparator + path2;
142 }
143
144
145 std::string Path::join(const std::string &path1,
146                        const std::string &path2,
147                        const std::string &path3)
148 {
149     // TODO: Remove extra separators if they are present in the input paths.
150     return path1 + cDirSeparator + path2 + cDirSeparator + path3;
151 }
152
153 std::string Path::getParentPath(const std::string &path)
154 {
155     size_t pos = path.find_last_of(cDirSeparators);
156     if (pos == std::string::npos)
157     {
158         return std::string();
159     }
160     return path.substr(0, pos);
161 }
162
163 std::string Path::getFilename(const std::string &path)
164 {
165     size_t pos = path.find_last_of(cDirSeparators);
166     if (pos == std::string::npos)
167     {
168         return path;
169     }
170     return path.substr(pos+1);
171 }
172
173 std::string Path::normalize(const std::string &path)
174 {
175     std::string result(path);
176     // TODO: Remove . and .. entries.
177     if (DIR_SEPARATOR != '/')
178     {
179         std::replace(result.begin(), result.end(), '/', DIR_SEPARATOR);
180     }
181 #ifdef GMX_NATIVE_WINDOWS
182     if (std::isalpha(result[0]) && result[1] == ':')
183     {
184         result[0] = std::toupper(result[0]);
185     }
186 #endif
187     return result;
188 }
189
190 bool Path::exists(const char *path)
191 {
192     return gmx_fexist(path);
193 }
194
195 bool Path::exists(const std::string &path)
196 {
197     return exists(path.c_str());
198 }
199
200 std::string Path::getWorkingDirectory()
201 {
202     // TODO: Use exceptions instead of gmx_fatal().
203     char cwd[GMX_PATH_MAX];
204     gmx_getcwd(cwd, sizeof(cwd));
205     return cwd;
206 }
207
208 void Path::splitPathEnvironment(const std::string        &pathEnv,
209                                 std::vector<std::string> *result)
210 {
211     size_t prevPos = 0;
212     size_t separator;
213     do
214     {
215         separator = pathEnv.find(cPathSeparator, prevPos);
216         result->push_back(pathEnv.substr(prevPos, separator - prevPos));
217         prevPos = separator + 1;
218     }
219     while (separator != std::string::npos);
220 }
221
222 std::vector<std::string> Path::getExecutablePaths()
223 {
224     std::vector<std::string> result;
225 #ifdef GMX_NATIVE_WINDOWS
226     // Add the local dir since it is not in the path on Windows.
227     result.push_back("");
228 #endif
229     const char *path = std::getenv("PATH");
230     if (path != NULL)
231     {
232         splitPathEnvironment(path, &result);
233     }
234     return result;
235 }
236
237 std::string Path::resolveSymlinks(const std::string &path)
238 {
239     std::string result(path);
240 #ifndef GMX_NATIVE_WINDOWS
241     char        buf[GMX_PATH_MAX];
242     int         length;
243     while ((length = readlink(result.c_str(), buf, sizeof(buf)-1)) > 0)
244     {
245         buf[length] = '\0';
246         if (isAbsolute(buf))
247         {
248             result = buf;
249         }
250         else
251         {
252             result = join(getParentPath(result), buf);
253         }
254     }
255 #endif
256     return result;
257 }
258
259
260 /********************************************************************
261  * Directory
262  */
263
264 int Directory::create(const char *path)
265 {
266     if (Directory::exists(path))
267     {
268         return 0;
269     }
270 #ifdef GMX_NATIVE_WINDOWS
271     if (_mkdir(path))
272 #else
273     if (mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IWOTH) != 0)
274 #endif
275     {
276         // TODO: Proper error handling.
277         return -1;
278     }
279     return 0;
280 }
281
282
283 int Directory::create(const std::string &path)
284 {
285     return create(path.c_str());
286 }
287
288
289 bool Directory::exists(const char *path)
290 {
291     struct stat info;
292     if (stat(path, &info) != 0)
293     {
294         if (errno != ENOENT && errno != ENOTDIR)
295         {
296             // TODO: Proper error handling.
297         }
298         return false;
299     }
300 #ifdef GMX_NATIVE_WINDOWS
301     return ((_S_IFDIR & info.st_mode) != 0);
302 #else
303     return S_ISDIR(info.st_mode);
304 #endif
305 }
306
307
308 bool Directory::exists(const std::string &path)
309 {
310     return exists(path.c_str());
311 }
312
313 } // namespace gmx