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 <algorithm>
24 #include <vector>
25 #include <sstream>
26 #include <cstring>
27 #include <cctype>
28 
29 /** Is the filesystem case insensitive? */
31 {
32 #ifdef _WIN32
33  return true;
34 #else
35  // TODO: Non-windows filesystems might be case insensitive
36  return false;
37 #endif
38 }
39 
40 std::string Path::toNativeSeparators(std::string path)
41 {
42 #if defined(_WIN32)
43  char separ = '/';
44  char native = '\\';
45 #else
46  char separ = '\\';
47  char native = '/';
48 #endif
49  std::replace(path.begin(), path.end(), separ, native);
50  return path;
51 }
52 
53 std::string Path::fromNativeSeparators(std::string path)
54 {
55  char nonnative = '\\';
56  char newsepar = '/';
57  std::replace(path.begin(), path.end(), nonnative, newsepar);
58  return path;
59 }
60 
61 std::string Path::simplifyPath(std::string originalPath)
62 {
63  const bool isUnc = originalPath.compare(0,2,"//") == 0;
64 
65  // Remove ./, .//, ./// etc. at the beginning
66  while (originalPath.compare(0,2,"./") == 0) { // remove "./././"
67  size_t toErase = originalPath.find_first_not_of("/",2);
68  originalPath = originalPath.erase(0, toErase);
69  }
70 
71  std::string subPath = "";
72  std::vector<std::string> pathParts;
73  for (std::size_t i = 0; i < originalPath.size(); ++i) {
74  if (originalPath[i] == '/' || originalPath[i] == '\\') {
75  if (subPath.length() > 0) {
76  pathParts.push_back(subPath);
77  subPath = "";
78  }
79 
80  pathParts.push_back(std::string(1 , originalPath[i]));
81  } else
82  subPath.append(1, originalPath[i]);
83  }
84 
85  if (subPath.length() > 0)
86  pathParts.push_back(subPath);
87 
88  // First filter out all double slashes
89  for (unsigned int i = 1; i < pathParts.size(); ++i) {
90  if (i > 0 && pathParts[i] == "/" && pathParts[i-1] == "/") {
91  pathParts.erase(pathParts.begin() + static_cast<int>(i) - 1);
92  --i;
93  }
94  }
95 
96  for (unsigned int i = 1; i < pathParts.size(); ++i) {
97  if (i > 1 && pathParts[i-2] != ".." && pathParts[i] == ".." && pathParts.size() > i + 1) {
98  pathParts.erase(pathParts.begin() + static_cast<int>(i) + 1);
99  pathParts.erase(pathParts.begin() + static_cast<int>(i));
100  pathParts.erase(pathParts.begin() + static_cast<int>(i) - 1);
101  pathParts.erase(pathParts.begin() + static_cast<int>(i) - 2);
102  i = 0;
103  } else if (i > 0 && pathParts[i] == ".") {
104  pathParts.erase(pathParts.begin() + static_cast<int>(i));
105  i = 0;
106  } else if (i > 0 && pathParts[i] == "/" && pathParts[i-1] == "/") {
107  pathParts.erase(pathParts.begin() + static_cast<int>(i) - 1);
108  i = 0;
109  }
110  }
111 
112  if (isUnc) {
113  // Restore the leading double slash
114  pathParts.insert(pathParts.begin(), "/");
115  }
116 
117  std::ostringstream oss;
118  for (std::vector<std::string>::size_type i = 0; i < pathParts.size(); ++i) {
119  oss << pathParts[i];
120  }
121 
122  return oss.str();
123 }
124 
125 std::string Path::getPathFromFilename(const std::string &filename)
126 {
127  std::size_t pos = filename.find_last_of("\\/");
128 
129  if (pos != std::string::npos)
130  return filename.substr(0, 1 + pos);
131 
132  return "";
133 }
134 
135 
136 bool Path::sameFileName(const std::string &fname1, const std::string &fname2)
137 {
138 #if defined(__linux__) || defined(__sun) || defined(__hpux)
139  return bool(fname1 == fname2);
140 #elif defined(_MSC_VER) || (defined(__GNUC__) && defined(_WIN32))
141  return bool(_stricmp(fname1.c_str(), fname2.c_str()) == 0);
142 #elif defined(__GNUC__)
143  return bool(strcasecmp(fname1.c_str(), fname2.c_str()) == 0);
144 #elif defined(__BORLANDC__)
145  return bool(stricmp(fname1.c_str(), fname2.c_str()) == 0);
146 #else
147 #error Platform filename compare function needed
148 #endif
149 }
150 
151 // This wrapper exists because Sun's CC does not allow a static_cast
152 // from extern "C" int(*)(int) to int(*)(int).
153 static int tolowerWrapper(int c)
154 {
155  return std::tolower(c);
156 }
157 
158 std::string Path::removeQuotationMarks(std::string path)
159 {
160  path.erase(std::remove(path.begin(), path.end(), '\"'), path.end());
161  return path;
162 }
163 
164 std::string Path::getFilenameExtension(const std::string &path)
165 {
166  const std::string::size_type dotLocation = path.find_last_of('.');
167  if (dotLocation == std::string::npos)
168  return "";
169 
170  std::string extension = path.substr(dotLocation);
172  // on a case insensitive filesystem the case doesn't matter so
173  // let's return the extension in lowercase
174  std::transform(extension.begin(), extension.end(), extension.begin(), tolowerWrapper);
175  }
176  return extension;
177 }
178 
179 std::string Path::getFilenameExtensionInLowerCase(const std::string &path)
180 {
181  std::string extension = getFilenameExtension(path);
182  std::transform(extension.begin(), extension.end(), extension.begin(), tolowerWrapper);
183  return extension;
184 }
185 
186 std::string Path::getRelativePath(const std::string& absolutePath, const std::vector<std::string>& basePaths)
187 {
188  for (std::vector<std::string>::const_iterator i = basePaths.begin(); i != basePaths.end(); ++i) {
189  if (absolutePath == *i || i->empty()) // Seems to be a file, or path is empty
190  continue;
191 
192  bool endsWithSep = (*i)[i->length()-1] == '/';
193  if (absolutePath.compare(0, i->length(), *i) == 0 && absolutePath[i->length() - (endsWithSep?1:0)] == '/') {
194  std::string rest = absolutePath.substr(i->length() + (endsWithSep?0:1));
195  return rest;
196  }
197  }
198  return absolutePath;
199 }
200 
201 bool Path::isC(const std::string &path)
202 {
203  // In unix, ".C" is considered C++ file
204  const std::string extension = getFilenameExtension(path);
205  return (extension == ".c");
206 }
207 
208 bool Path::isCPP(const std::string &path)
209 {
210  const std::string extension = getFilenameExtensionInLowerCase(path);
211  if (extension == ".cpp" ||
212  extension == ".cxx" ||
213  extension == ".cc" ||
214  extension == ".c++" ||
215  extension == ".hpp" ||
216  extension == ".hxx" ||
217  extension == ".hh" ||
218  extension == ".tpp" ||
219  extension == ".txx") {
220  return true;
221  }
222 
223  // In unix, ".C" is considered C++ file
224  return (getFilenameExtension(path) == ".C");
225 }
226 
227 bool Path::acceptFile(const std::string &path, const std::set<std::string> &extra)
228 {
229  return !Path::isHeader(path) && (Path::isCPP(path) || Path::isC(path) || extra.find(getFilenameExtension(path)) != extra.end());
230 }
231 
232 bool Path::isHeader(const std::string &path)
233 {
234  const std::string extension = getFilenameExtensionInLowerCase(path);
235  return (extension.compare(0, 2, ".h") == 0);
236 }
237 
238 std::string Path::getAbsoluteFilePath(const std::string& filePath)
239 {
240  std::string absolute_path;
241 #ifdef _WIN32
242  char absolute[_MAX_PATH];
243  if (_fullpath(absolute, filePath.c_str(), _MAX_PATH))
244  absolute_path = absolute;
245 #elif defined(__linux__) || defined(__sun) || defined(__hpux) || defined(__GNUC__)
246  char * absolute = realpath(filePath.c_str(), nullptr);
247  if (absolute)
248  absolute_path = absolute;
249  free(absolute);
250 #else
251 #error Platform absolute path function needed
252 #endif
253  return absolute_path;
254 }
static bool sameFileName(const std::string &fname1, const std::string &fname2)
Compare filenames to see if they are the same.
Definition: path.cpp:136
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:125
static std::string fromNativeSeparators(std::string path)
Convert path to use internal path separators.
Definition: path.cpp:53
static bool acceptFile(const std::string &filename)
Check if the file extension indicates that it's a C/C++ source file.
Definition: path.h:120
static std::string getAbsoluteFilePath(const std::string &filePath)
Get an absolute file path from a relative one.
Definition: path.cpp:238
static std::string simplifyPath(std::string originalPath)
Simplify path "foo/bar/.." => "foo".
Definition: path.cpp:61
static bool isHeader(const std::string &path)
Is filename a header based on file extension.
Definition: path.cpp:232
static bool isC(const std::string &path)
Identify language based on file extension.
Definition: path.cpp:201
static int tolowerWrapper(int c)
Definition: path.cpp:153
static bool caseInsensitiveFilesystem()
Is the filesystem case insensitive?
Definition: path.cpp:30
static bool isCPP(const std::string &extensionInLowerCase)
Identify language based on file extension.
Definition: path.cpp:208
static std::string getFilenameExtensionInLowerCase(const std::string &path)
Get an extension of the filename in lower case.
Definition: path.cpp:179
static std::string getFilenameExtension(const std::string &path)
Get an extension of the filename.
Definition: path.cpp:164
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:186
static std::string removeQuotationMarks(std::string path)
Remove quotation marks (") from the path.
Definition: path.cpp:158
static std::string toNativeSeparators(std::string path)
Convert path to use native separators.
Definition: path.cpp:40