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