1 /*-------------------------------------------------------------------------
2  * drawElements C++ Base Library
3  * -----------------------------
4  *
5  * Copyright 2014 The Android Open Source Project
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  *//*!
20  * \file
21  * \brief Filesystem path class.
22  *//*--------------------------------------------------------------------*/
23 
24 #include "deFilePath.hpp"
25 
26 #include <vector>
27 #include <stdexcept>
28 
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 
32 #if (DE_OS == DE_OS_WIN32)
33 #	define VC_EXTRALEAN
34 #	define WIN32_LEAN_AND_MEAN
35 #	define NOMINMAX
36 #	include <windows.h>
37 #endif
38 
39 using std::string;
40 
41 namespace de
42 {
43 
44 #if (DE_OS == DE_OS_WIN32)
45 	const std::string FilePath::separator = "\\";
46 #else
47 	const std::string FilePath::separator = "/";
48 #endif
49 
FilePath(const std::vector<std::string> & components)50 FilePath::FilePath (const std::vector<std::string>& components)
51 {
52 	for (int ndx = 0; ndx < (int)components.size(); ndx++)
53 	{
54 		if (ndx > 0)
55 			m_path += separator;
56 		m_path += components[ndx];
57 	}
58 }
59 
split(std::vector<std::string> & components) const60 void FilePath::split (std::vector<std::string>& components) const
61 {
62 	components.clear();
63 
64 	int curCompStart = 0;
65 	int pos;
66 
67 	for (pos = 0; pos < (int)m_path.length(); pos++)
68 	{
69 		char c = m_path[pos];
70 
71 		if (isSeparator(c))
72 		{
73 			if (pos - curCompStart > 0)
74 				components.push_back(m_path.substr(curCompStart, pos - curCompStart));
75 
76 			curCompStart = pos+1;
77 		}
78 	}
79 
80 	if (pos - curCompStart > 0)
81 		components.push_back(m_path.substr(curCompStart, pos - curCompStart));
82 }
83 
normalize(void)84 FilePath& FilePath::normalize (void)
85 {
86 	bool						rootPath	= isRootPath();
87 	bool						winNetPath	= isWinNetPath();
88 	bool						hasDrive	= beginsWithDrive();
89 	std::vector<std::string>	components;
90 	split(components);
91 
92 	m_path = "";
93 
94 	int numUp = 0;
95 
96 	// Do in reverse order and eliminate any . or .. components
97 	for (int ndx = (int)components.size()-1; ndx >= 0; ndx--)
98 	{
99 		const std::string comp = components[ndx];
100 		if (comp == "..")
101 			numUp += 1;
102 		else if (comp == ".")
103 			continue;
104 		else if (numUp > 0)
105 			numUp -= 1; // Skip part
106 		else
107 		{
108 			if (m_path.length() > 0)
109 				m_path = comp + separator + m_path;
110 			else
111 				m_path = comp;
112 		}
113 	}
114 
115 	// Append necessary ".." components
116 	while (numUp--)
117 	{
118 		if (m_path.length() > 0)
119 			m_path = ".." + separator + m_path;
120 		else
121 			m_path = "..";
122 	}
123 
124 	if (winNetPath)
125 		m_path = separator + separator + m_path;
126 	else if (rootPath && !hasDrive)
127 		m_path = separator + m_path;
128 
129 	if (m_path.length() == 0 && !components.empty())
130 		m_path = "."; // Composed of "." components only
131 
132 	return *this;
133 }
134 
normalize(const FilePath & path)135 FilePath FilePath::normalize (const FilePath& path)
136 {
137 	return FilePath(path).normalize();
138 }
139 
getBaseName(void) const140 std::string FilePath::getBaseName (void) const
141 {
142 	std::vector<std::string> components;
143 	split(components);
144 	return !components.empty() ? components[components.size()-1] : std::string("");
145 }
146 
getDirName(void) const147 std::string	FilePath::getDirName (void) const
148 {
149 	std::vector<std::string> components;
150 	split(components);
151 	if (components.size() > 1)
152 	{
153 		components.pop_back();
154 		return FilePath(components).getPath();
155 	}
156 	else if (isAbsolutePath())
157 		return separator;
158 	else
159 		return std::string(".");
160 }
161 
getFileExtension(void) const162 std::string FilePath::getFileExtension (void) const
163 {
164 	std::string baseName = getBaseName();
165 	size_t dotPos = baseName.find_last_of('.');
166 	if (dotPos == std::string::npos)
167 		return std::string("");
168 	else
169 		return baseName.substr(dotPos+1);
170 }
171 
exists(void) const172 bool FilePath::exists (void) const
173 {
174 	FilePath	normPath	= FilePath::normalize(*this);
175 	struct		stat		st;
176 	int			result		= stat(normPath.getPath(), &st);
177 	return result == 0;
178 }
179 
getType(void) const180 FilePath::Type FilePath::getType (void) const
181 {
182 	FilePath	normPath	= FilePath::normalize(*this);
183 	struct		stat		st;
184 	int			result		= stat(normPath.getPath(), &st);
185 
186 	if (result != 0)
187 		return TYPE_UNKNOWN;
188 
189 	int type = st.st_mode & S_IFMT;
190 	if (type == S_IFREG)
191 		return TYPE_FILE;
192 	else if (type == S_IFDIR)
193 		return TYPE_DIRECTORY;
194 	else
195 		return TYPE_UNKNOWN;
196 }
197 
beginsWithDrive(void) const198 bool FilePath::beginsWithDrive (void) const
199 {
200 	for (int ndx = 0; ndx < (int)m_path.length(); ndx++)
201 	{
202 		if (m_path[ndx] == ':' && ndx+1 < (int)m_path.length() && isSeparator(m_path[ndx+1]))
203 			return true; // First part is drive letter.
204 		if (isSeparator(m_path[ndx]))
205 			return false;
206 	}
207 	return false;
208 }
209 
isAbsolutePath(void) const210 bool FilePath::isAbsolutePath (void) const
211 {
212 	return isRootPath() || isWinNetPath() || beginsWithDrive();
213 }
214 
FilePath_selfTest(void)215 void FilePath_selfTest (void)
216 {
217 	DE_TEST_ASSERT(!FilePath(".").isAbsolutePath());
218 	DE_TEST_ASSERT(!FilePath("..\\foo").isAbsolutePath());
219 	DE_TEST_ASSERT(!FilePath("foo").isAbsolutePath());
220 	DE_TEST_ASSERT(FilePath("\\foo/bar").isAbsolutePath());
221 	DE_TEST_ASSERT(FilePath("/foo").isAbsolutePath());
222 	DE_TEST_ASSERT(FilePath("\\").isAbsolutePath());
223 	DE_TEST_ASSERT(FilePath("\\\\net\\loc").isAbsolutePath());
224 	DE_TEST_ASSERT(FilePath("C:\\file.txt").isAbsolutePath());
225 	DE_TEST_ASSERT(FilePath("c:/file.txt").isAbsolutePath());
226 
227 	DE_TEST_ASSERT(string(".") == FilePath(".//.").normalize().getPath());
228 	DE_TEST_ASSERT(string(".") == FilePath(".").normalize().getPath());
229 	DE_TEST_ASSERT((string("..") + FilePath::separator + "test") == FilePath("foo/../bar/../../test").normalize().getPath());
230 	DE_TEST_ASSERT((FilePath::separator + "foo" + FilePath::separator + "foo.txt") == FilePath("/foo\\bar/..\\dir\\..\\foo.txt").normalize().getPath());
231 	DE_TEST_ASSERT((string("c:") + FilePath::separator + "foo" + FilePath::separator + "foo.txt") == FilePath("c:/foo\\bar/..\\dir\\..\\foo.txt").normalize().getPath());
232 	DE_TEST_ASSERT((FilePath::separator + FilePath::separator + "foo" + FilePath::separator + "foo.txt") == FilePath("\\\\foo\\bar/..\\dir\\..\\foo.txt").normalize().getPath());
233 
234 	DE_TEST_ASSERT(FilePath("foo/bar"		).getBaseName()	== "bar");
235 	DE_TEST_ASSERT(FilePath("foo/bar/"		).getBaseName()	== "bar");
236 	DE_TEST_ASSERT(FilePath("foo\\bar"		).getBaseName()	== "bar");
237 	DE_TEST_ASSERT(FilePath("foo\\bar\\"	).getBaseName()	== "bar");
238 	DE_TEST_ASSERT(FilePath("foo/bar"		).getDirName()	== "foo");
239 	DE_TEST_ASSERT(FilePath("foo/bar/"		).getDirName()	== "foo");
240 	DE_TEST_ASSERT(FilePath("foo\\bar"		).getDirName()	== "foo");
241 	DE_TEST_ASSERT(FilePath("foo\\bar\\"	).getDirName()	== "foo");
242 }
243 
createDirectoryImpl(const char * path)244 static void createDirectoryImpl (const char* path)
245 {
246 #if (DE_OS == DE_OS_WIN32)
247 	if (!CreateDirectory(path, DE_NULL))
248 		throw std::runtime_error("Failed to create directory");
249 #elif (DE_OS == DE_OS_UNIX) || (DE_OS == DE_OS_OSX) || (DE_OS == DE_OS_IOS) || (DE_OS == DE_OS_ANDROID) || (DE_OS == DE_OS_SYMBIAN)
250 	if (mkdir(path, 01777) != 0)
251 		throw std::runtime_error("Failed to create directory");
252 #else
253 #	error Implement createDirectoryImpl() for your platform.
254 #endif
255 }
256 
createDirectory(const char * path)257 void createDirectory (const char* path)
258 {
259 	FilePath	dirPath		= FilePath::normalize(path);
260 	FilePath	parentPath	(dirPath.getDirName());
261 
262 	if (dirPath.exists())
263 		throw std::runtime_error("Destination exists already");
264 	else if (!parentPath.exists())
265 		throw std::runtime_error("Parent directory doesn't exist");
266 	else if (parentPath.getType() != FilePath::TYPE_DIRECTORY)
267 		throw std::runtime_error("Parent is not directory");
268 
269 	createDirectoryImpl(path);
270 }
271 
createDirectoryAndParents(const char * path)272 void createDirectoryAndParents (const char* path)
273 {
274 	std::vector<std::string>	createPaths;
275 	FilePath					curPath		(path);
276 
277 	if (curPath.exists())
278 		throw std::runtime_error("Destination exists already");
279 
280 	while (!curPath.exists())
281 	{
282 		createPaths.push_back(curPath.getPath());
283 
284 		std::string parent = curPath.getDirName();
285 		DE_CHECK_RUNTIME_ERR(parent != curPath.getPath());
286 		curPath = FilePath(parent);
287 	}
288 
289 	// Create in reverse order.
290 	for (std::vector<std::string>::const_reverse_iterator parentIter = createPaths.rbegin(); parentIter != createPaths.rend(); parentIter++)
291 		createDirectory(parentIter->c_str());
292 }
293 
294 } // de
295