Cppcheck
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
path.cpp
Go to the documentation of this file.
1 /*
2  * Cppcheck - A tool for static C/C++ code analysis
3  * Copyright (C) 2007-2016 Cppcheck team.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #if defined(__GNUC__) && (defined(_WIN32) || defined(__CYGWIN__))
20 #undef __STRICT_ANSI__
21 #endif
22 #include "path.h"
23 #include "utils.h"
24 
25 #include <algorithm>
26 #include <cctype>
27 #include <cstdlib>
28 #include <cstring>
29 #include <sstream>
30 
31 #ifndef _WIN32
32 #include <unistd.h>
33 #else
34 #include <direct.h>
35 #endif
36 #if defined(__CYGWIN__)
37 #include <strings.h>
38 #endif
39 
40 #include <simplecpp.h>
41 
42 /** Is the filesystem case insensitive? */
44 {
45 #ifdef _WIN32
46  return true;
47 #else
48  // TODO: Non-windows filesystems might be case insensitive
49  return false;
50 #endif
51 }
52 
53 std::string Path::toNativeSeparators(std::string path)
54 {
55 #if defined(_WIN32)
56  const char separ = '/';
57  const char native = '\\';
58 #else
59  const char separ = '\\';
60  const char native = '/';
61 #endif
62  std::replace(path.begin(), path.end(), separ, native);
63  return path;
64 }
65 
66 std::string Path::fromNativeSeparators(std::string path)
67 {
68  const char nonnative = '\\';
69  const char newsepar = '/';
70  std::replace(path.begin(), path.end(), nonnative, newsepar);
71  return path;
72 }
73 
74 std::string Path::simplifyPath(std::string originalPath)
75 {
76  return simplecpp::simplifyPath(originalPath);
77 }
78 
79 std::string Path::getPathFromFilename(const std::string &filename)
80 {
81  const std::size_t pos = filename.find_last_of("\\/");
82 
83  if (pos != std::string::npos)
84  return filename.substr(0, 1 + pos);
85 
86  return "";
87 }
88 
89 bool Path::sameFileName(const std::string &fname1, const std::string &fname2)
90 {
91  return caseInsensitiveFilesystem() ? (caseInsensitiveStringCompare(fname1, fname2) == 0) : (fname1 == fname2);
92 }
93 
94 // This wrapper exists because Sun's CC does not allow a static_cast
95 // from extern "C" int(*)(int) to int(*)(int).
96 static int tolowerWrapper(int c)
97 {
98  return std::tolower(c);
99 }
100 
101 std::string Path::removeQuotationMarks(std::string path)
102 {
103  path.erase(std::remove(path.begin(), path.end(), '\"'), path.end());
104  return path;
105 }
106 
107 std::string Path::getFilenameExtension(const std::string &path)
108 {
109  const std::string::size_type dotLocation = path.find_last_of('.');
110  if (dotLocation == std::string::npos)
111  return "";
112 
113  std::string extension = path.substr(dotLocation);
115  // on a case insensitive filesystem the case doesn't matter so
116  // let's return the extension in lowercase
117  std::transform(extension.begin(), extension.end(), extension.begin(), tolowerWrapper);
118  }
119  return extension;
120 }
121 
122 std::string Path::getFilenameExtensionInLowerCase(const std::string &path)
123 {
124  std::string extension = getFilenameExtension(path);
125  std::transform(extension.begin(), extension.end(), extension.begin(), tolowerWrapper);
126  return extension;
127 }
128 
129 std::string Path::getCurrentPath()
130 {
131  char currentPath[4096];
132 
133 #ifndef _WIN32
134  if (getcwd(currentPath, 4096) != nullptr)
135 #else
136  if (_getcwd(currentPath, 4096) != 0)
137 #endif
138  return std::string(currentPath);
139 
140  return emptyString;
141 }
142 
143 bool Path::isAbsolute(const std::string& path)
144 {
145  const std::string& nativePath = toNativeSeparators(path);
146 
147 #ifdef _WIN32
148  if (path.length() < 2)
149  return false;
150 
151  // On Windows, 'C:\foo\bar' is an absolute path, while 'C:foo\bar' is not
152  if (nativePath.compare(0, 2, "\\\\") == 0 || (std::isalpha(nativePath[0]) != 0 && nativePath.compare(1, 2, ":\\") == 0))
153  return true;
154 #else
155  if (!nativePath.empty() && nativePath[0] == '/')
156  return true;
157 #endif
158 
159  return false;
160 }
161 
162 std::string Path::getRelativePath(const std::string& absolutePath, const std::vector<std::string>& basePaths)
163 {
164  for (std::vector<std::string>::const_iterator i = basePaths.begin(); i != basePaths.end(); ++i) {
165  if (absolutePath == *i || i->empty()) // Seems to be a file, or path is empty
166  continue;
167 
168  bool endsWithSep = endsWith(*i,'/');
169  if (absolutePath.compare(0, i->length(), *i) == 0 && absolutePath[i->length() - (endsWithSep?1:0)] == '/') {
170  std::string rest = absolutePath.substr(i->length() + (endsWithSep?0:1));
171  return rest;
172  }
173  }
174  return absolutePath;
175 }
176 
177 bool Path::isC(const std::string &path)
178 {
179  // In unix, ".C" is considered C++ file
180  const std::string extension = getFilenameExtension(path);
181  return extension == ".c" ||
182  extension == ".cl";
183 }
184 
185 bool Path::isCPP(const std::string &path)
186 {
187  const std::string extension = getFilenameExtensionInLowerCase(path);
188  return extension == ".cpp" ||
189  extension == ".cxx" ||
190  extension == ".cc" ||
191  extension == ".c++" ||
192  extension == ".hpp" ||
193  extension == ".hxx" ||
194  extension == ".hh" ||
195  extension == ".tpp" ||
196  extension == ".txx" ||
197  getFilenameExtension(path) == ".C"; // In unix, ".C" is considered C++ file
198 }
199 
200 bool Path::acceptFile(const std::string &path, const std::set<std::string> &extra)
201 {
202  return !Path::isHeader(path) && (Path::isCPP(path) || Path::isC(path) || extra.find(getFilenameExtension(path)) != extra.end());
203 }
204 
205 bool Path::isHeader(const std::string &path)
206 {
207  const std::string extension = getFilenameExtensionInLowerCase(path);
208  return (extension.compare(0, 2, ".h") == 0);
209 }
210 
211 std::string Path::getAbsoluteFilePath(const std::string& filePath)
212 {
213  std::string absolute_path;
214 #ifdef _WIN32
215  char absolute[_MAX_PATH];
216  if (_fullpath(absolute, filePath.c_str(), _MAX_PATH))
217  absolute_path = absolute;
218 #elif defined(__linux__) || defined(__sun) || defined(__hpux) || defined(__GNUC__)
219  char * absolute = realpath(filePath.c_str(), nullptr);
220  if (absolute)
221  absolute_path = absolute;
222  free(absolute);
223 #else
224 #error Platform absolute path function needed
225 #endif
226  return absolute_path;
227 }
228 
229 std::string Path::stripDirectoryPart(const std::string &file)
230 {
231 #if defined(_WIN32) && !defined(__MINGW32__)
232  const char native = '\\';
233 #else
234  const char native = '/';
235 #endif
236 
237  const std::string::size_type p = file.rfind(native);
238  if (p != std::string::npos) {
239  return file.substr(p + 1);
240  }
241  return file;
242 }
static bool sameFileName(const std::string &fname1, const std::string &fname2)
Compare filenames to see if they are the same.
Definition: path.cpp:89
static std::string getPathFromFilename(const std::string &filename)
Lookup the path part from a filename (e.g., '/tmp/a.h' -> '/tmp/', 'a.h' -> '')
Definition: path.cpp:79
static bool isAbsolute(const std::string &path)
Check if given path is absolute.
Definition: path.cpp:143
static std::string fromNativeSeparators(std::string path)
Convert path to use internal path separators.
Definition: path.cpp:66
static bool acceptFile(const std::string &filename)
Check if the file extension indicates that it's a C/C++ source file.
Definition: path.h:134
static std::string getAbsoluteFilePath(const std::string &filePath)
Get an absolute file path from a relative one.
Definition: path.cpp:211
static std::string getCurrentPath()
Returns the absolute path of current working directory.
Definition: path.cpp:129
static std::string simplifyPath(std::string originalPath)
Simplify path "foo/bar/.." => "foo".
Definition: path.cpp:74
static const std::string emptyString
Definition: config.h:23
static bool isHeader(const std::string &path)
Is filename a header based on file extension.
Definition: path.cpp:205
static bool isC(const std::string &path)
Identify language based on file extension.
Definition: path.cpp:177
static std::string stripDirectoryPart(const std::string &file)
Get filename without a directory path part.
Definition: path.cpp:229
static int tolowerWrapper(int c)
Definition: path.cpp:96
bool endsWith(const std::string &str, char c)
Definition: utils.h:61
static bool caseInsensitiveFilesystem()
Is the filesystem case insensitive?
Definition: path.cpp:43
static int caseInsensitiveStringCompare(const std::string &lhs, const std::string &rhs)
Definition: utils.h:82
static std::string getFilenameExtensionInLowerCase(const std::string &path)
Get an extension of the filename in lower case.
Definition: path.cpp:122
static std::string getFilenameExtension(const std::string &path)
Get an extension of the filename.
Definition: path.cpp:107
static std::string getRelativePath(const std::string &absolutePath, const std::vector< std::string > &basePaths)
Create a relative path from an absolute one, if absolute path is inside the basePaths.
Definition: path.cpp:162
static bool isCPP(const std::string &path)
Identify language based on file extension.
Definition: path.cpp:185
static std::string removeQuotationMarks(std::string path)
Remove quotation marks (") from the path.
Definition: path.cpp:101
static std::string toNativeSeparators(std::string path)
Convert path to use native separators.
Definition: path.cpp:53