filepath.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /*
  2. * Copyright 2010-2018 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
  4. */
  5. #include "bx_p.h"
  6. #include <bx/file.h>
  7. #include <bx/os.h>
  8. #include <bx/readerwriter.h>
  9. #if !BX_CRT_NONE
  10. # include <stdio.h> // remove
  11. # include <dirent.h> // opendir
  12. # if BX_CRT_MSVC
  13. # include <direct.h> // _getcwd
  14. # else
  15. # include <sys/stat.h> // mkdir
  16. # include <unistd.h> // getcwd
  17. # endif // BX_CRT_MSVC
  18. #endif // 0
  19. #if BX_PLATFORM_WINDOWS
  20. extern "C" __declspec(dllimport) unsigned long __stdcall GetTempPathA(unsigned long _max, char* _ptr);
  21. #endif // BX_PLATFORM_WINDOWS
  22. namespace bx
  23. {
  24. static bool isPathSeparator(char _ch)
  25. {
  26. return false
  27. || '/' == _ch
  28. || '\\' == _ch
  29. ;
  30. }
  31. static int32_t normalizeFilePath(char* _dst, int32_t _dstSize, const char* _src, int32_t _num)
  32. {
  33. // Reference(s):
  34. // - Lexical File Names in Plan 9 or Getting Dot-Dot Right
  35. // https://web.archive.org/web/20180629044444/https://9p.io/sys/doc/lexnames.html
  36. const int32_t num = strLen(_src, _num);
  37. if (0 == num)
  38. {
  39. return strCopy(_dst, _dstSize, ".");
  40. }
  41. int32_t size = 0;
  42. StaticMemoryBlockWriter writer(_dst, _dstSize);
  43. Error err;
  44. int32_t idx = 0;
  45. int32_t dotdot = 0;
  46. if (2 <= num
  47. && ':' == _src[1])
  48. {
  49. size += write(&writer, toUpper(_src[idx]), &err);
  50. size += write(&writer, ':', &err);
  51. idx += 2;
  52. dotdot = size;
  53. }
  54. const int32_t slashIdx = idx;
  55. bool rooted = isPathSeparator(_src[idx]);
  56. if (rooted)
  57. {
  58. size += write(&writer, '/', &err);
  59. ++idx;
  60. dotdot = size;
  61. }
  62. bool trailingSlash = false;
  63. while (idx < num && err.isOk() )
  64. {
  65. switch (_src[idx])
  66. {
  67. case '/':
  68. case '\\':
  69. ++idx;
  70. trailingSlash = idx == num;
  71. break;
  72. case '.':
  73. if (idx+1 == num
  74. || isPathSeparator(_src[idx+1]) )
  75. {
  76. ++idx;
  77. break;
  78. }
  79. if ('.' == _src[idx+1]
  80. && (idx+2 == num || isPathSeparator(_src[idx+2]) ) )
  81. {
  82. idx += 2;
  83. if (dotdot < size)
  84. {
  85. for (--size
  86. ; dotdot < size && !isPathSeparator(_dst[size])
  87. ; --size)
  88. {
  89. }
  90. seek(&writer, size, Whence::Begin);
  91. }
  92. else if (!rooted)
  93. {
  94. if (0 < size)
  95. {
  96. size += write(&writer, '/', &err);
  97. }
  98. size += write(&writer, "..", &err);
  99. dotdot = size;
  100. }
  101. break;
  102. }
  103. BX_FALLTHROUGH;
  104. default:
  105. if ( ( rooted && slashIdx+1 != size)
  106. || (!rooted && 0 != size) )
  107. {
  108. size += write(&writer, '/', &err);
  109. }
  110. for (; idx < num && !isPathSeparator(_src[idx]); ++idx)
  111. {
  112. size += write(&writer, _src[idx], &err);
  113. }
  114. break;
  115. }
  116. }
  117. if (0 == size)
  118. {
  119. size += write(&writer, '.', &err);
  120. }
  121. if (trailingSlash)
  122. {
  123. size += write(&writer, '/', &err);
  124. }
  125. write(&writer, '\0', &err);
  126. return size;
  127. }
  128. static bool getEnv(char* _out, uint32_t* _inOutSize, const StringView& _name, FileInfo::Enum _type)
  129. {
  130. uint32_t len = *_inOutSize;
  131. *_out = '\0';
  132. if (getEnv(_out, &len, _name) )
  133. {
  134. FileInfo fi;
  135. if (stat(_out, fi)
  136. && _type == fi.m_type)
  137. {
  138. *_inOutSize = len;
  139. return true;
  140. }
  141. }
  142. return false;
  143. }
  144. static char* pwd(char* _buffer, uint32_t _size)
  145. {
  146. #if BX_PLATFORM_PS4 \
  147. || BX_PLATFORM_XBOXONE \
  148. || BX_PLATFORM_WINRT \
  149. || BX_CRT_NONE
  150. BX_UNUSED(_buffer, _size);
  151. return NULL;
  152. #elif BX_CRT_MSVC
  153. return ::_getcwd(_buffer, (int32_t)_size);
  154. #else
  155. return ::getcwd(_buffer, _size);
  156. #endif // BX_COMPILER_
  157. }
  158. static bool getCurrentPath(char* _out, uint32_t* _inOutSize)
  159. {
  160. uint32_t len = *_inOutSize;
  161. if (NULL != pwd(_out, len))
  162. {
  163. *_inOutSize = strLen(_out);
  164. return true;
  165. }
  166. return false;
  167. }
  168. static bool getHomePath(char* _out, uint32_t* _inOutSize)
  169. {
  170. return false
  171. #if BX_PLATFORM_WINDOWS
  172. || getEnv(_out, _inOutSize, "USERPROFILE", FileInfo::Directory)
  173. #endif // BX_PLATFORM_WINDOWS
  174. || getEnv(_out, _inOutSize, "HOME", FileInfo::Directory)
  175. ;
  176. }
  177. static bool getTempPath(char* _out, uint32_t* _inOutSize)
  178. {
  179. #if BX_PLATFORM_WINDOWS
  180. uint32_t len = ::GetTempPathA(*_inOutSize, _out);
  181. bool result = len != 0 && len < *_inOutSize;
  182. *_inOutSize = len;
  183. return result;
  184. #else
  185. static const StringView s_tmp[] =
  186. {
  187. "TMPDIR",
  188. "TMP",
  189. "TEMP",
  190. "TEMPDIR",
  191. ""
  192. };
  193. for (const StringView* tmp = s_tmp; !tmp->isEmpty(); ++tmp)
  194. {
  195. uint32_t len = *_inOutSize;
  196. *_out = '\0';
  197. bool ok = getEnv(_out, &len, *tmp, FileInfo::Directory);
  198. if (ok
  199. && len != 0
  200. && len < *_inOutSize)
  201. {
  202. *_inOutSize = len;
  203. return ok;
  204. }
  205. }
  206. FileInfo fi;
  207. if (stat("/tmp", fi)
  208. && FileInfo::Directory == fi.m_type)
  209. {
  210. strCopy(_out, *_inOutSize, "/tmp");
  211. *_inOutSize = 4;
  212. return true;
  213. }
  214. return false;
  215. #endif // BX_PLATFORM_*
  216. }
  217. FilePath::FilePath()
  218. {
  219. set("");
  220. }
  221. FilePath::FilePath(Dir::Enum _dir)
  222. {
  223. set(_dir);
  224. }
  225. FilePath::FilePath(const char* _rhs)
  226. {
  227. set(_rhs);
  228. }
  229. FilePath::FilePath(const StringView& _filePath)
  230. {
  231. set(_filePath);
  232. }
  233. FilePath& FilePath::operator=(const StringView& _rhs)
  234. {
  235. set(_rhs);
  236. return *this;
  237. }
  238. void FilePath::clear()
  239. {
  240. if (!isEmpty() )
  241. {
  242. set("");
  243. }
  244. }
  245. void FilePath::set(Dir::Enum _dir)
  246. {
  247. char tmp[kMaxFilePath];
  248. uint32_t len = BX_COUNTOF(tmp);
  249. switch (_dir)
  250. {
  251. case Dir::Current:
  252. getCurrentPath(tmp, &len);
  253. break;
  254. case Dir::Temp:
  255. getTempPath(tmp, &len);
  256. break;
  257. case Dir::Home:
  258. getHomePath(tmp, &len);
  259. break;
  260. default:
  261. len = 0;
  262. break;
  263. }
  264. set(StringView(tmp, len) );
  265. }
  266. void FilePath::set(const StringView& _filePath)
  267. {
  268. normalizeFilePath(
  269. m_filePath
  270. , BX_COUNTOF(m_filePath)
  271. , _filePath.getPtr()
  272. , _filePath.getLength()
  273. );
  274. }
  275. void FilePath::join(const StringView& _str)
  276. {
  277. char tmp[kMaxFilePath];
  278. strCopy(tmp, BX_COUNTOF(tmp), m_filePath);
  279. strCat(tmp, BX_COUNTOF(tmp), "/");
  280. strCat(tmp, BX_COUNTOF(tmp), _str);
  281. set(tmp);
  282. }
  283. const char* FilePath::get() const
  284. {
  285. return m_filePath;
  286. }
  287. StringView FilePath::getPath() const
  288. {
  289. StringView end = strRFind(m_filePath, '/');
  290. if (!end.isEmpty() )
  291. {
  292. return StringView(m_filePath, end.getPtr()+1);
  293. }
  294. return StringView();
  295. }
  296. StringView FilePath::getFileName() const
  297. {
  298. StringView fileName = strRFind(m_filePath, '/');
  299. if (!fileName.isEmpty() )
  300. {
  301. return StringView(fileName.getPtr()+1);
  302. }
  303. return get();
  304. }
  305. StringView FilePath::getBaseName() const
  306. {
  307. const StringView fileName = getFileName();
  308. if (!fileName.isEmpty() )
  309. {
  310. StringView ext = strFind(fileName, '.');
  311. if (!ext.isEmpty() )
  312. {
  313. return StringView(fileName.getPtr(), ext.getPtr() );
  314. }
  315. return fileName;
  316. }
  317. return StringView();
  318. }
  319. StringView FilePath::getExt() const
  320. {
  321. const StringView fileName = getFileName();
  322. if (!fileName.isEmpty() )
  323. {
  324. return strFind(fileName, '.');
  325. }
  326. return StringView();
  327. }
  328. bool FilePath::isAbsolute() const
  329. {
  330. return '/' == m_filePath[0] // no drive letter
  331. || (':' == m_filePath[1] && '/' == m_filePath[2]) // with drive letter
  332. ;
  333. }
  334. bool FilePath::isEmpty() const
  335. {
  336. return 0 == strCmp(m_filePath, ".");
  337. }
  338. bool make(const FilePath& _filePath, Error* _err)
  339. {
  340. BX_ERROR_SCOPE(_err);
  341. if (!_err->isOk() )
  342. {
  343. return false;
  344. }
  345. #if BX_CRT_MSVC
  346. int32_t result = ::_mkdir(_filePath.get() );
  347. #elif BX_CRT_MINGW
  348. int32_t result = ::mkdir(_filePath.get());
  349. #elif BX_CRT_NONE
  350. BX_UNUSED(_filePath);
  351. int32_t result = -1;
  352. #else
  353. int32_t result = ::mkdir(_filePath.get(), 0700);
  354. #endif // BX_CRT_MSVC
  355. if (0 != result)
  356. {
  357. BX_ERROR_SET(_err, BX_ERROR_ACCESS, "The parent directory does not allow write permission to the process.");
  358. return false;
  359. }
  360. return true;
  361. }
  362. bool makeAll(const FilePath& _filePath, Error* _err)
  363. {
  364. BX_ERROR_SCOPE(_err);
  365. if (!_err->isOk() )
  366. {
  367. return false;
  368. }
  369. FileInfo fi;
  370. if (stat(_filePath, fi) )
  371. {
  372. if (FileInfo::Directory == fi.m_type)
  373. {
  374. return true;
  375. }
  376. BX_ERROR_SET(_err, BX_ERROR_NOT_DIRECTORY, "File already exist, and is not directory.");
  377. return false;
  378. }
  379. const StringView dir = strRTrim(_filePath.get(), "/");
  380. const StringView slash = strRFind(dir, '/');
  381. if (!slash.isEmpty()
  382. && slash.getPtr() - dir.getPtr() > 1)
  383. {
  384. if (!makeAll(StringView(dir.getPtr(), slash.getPtr() ), _err) )
  385. {
  386. return false;
  387. }
  388. }
  389. FilePath path(dir);
  390. return make(path, _err);
  391. }
  392. bool remove(const FilePath& _filePath, Error* _err)
  393. {
  394. BX_ERROR_SCOPE(_err);
  395. if (!_err->isOk() )
  396. {
  397. return false;
  398. }
  399. #if BX_CRT_MSVC
  400. int32_t result = -1;
  401. FileInfo fi;
  402. if (stat(_filePath, fi) )
  403. {
  404. if (FileInfo::Directory == fi.m_type)
  405. {
  406. result = ::_rmdir(_filePath.get() );
  407. }
  408. else
  409. {
  410. result = ::remove(_filePath.get() );
  411. }
  412. }
  413. #elif BX_CRT_NONE
  414. BX_UNUSED(_filePath);
  415. int32_t result = -1;
  416. #else
  417. int32_t result = ::remove(_filePath.get() );
  418. #endif // BX_CRT_MSVC
  419. if (0 != result)
  420. {
  421. BX_ERROR_SET(_err, BX_ERROR_ACCESS, "The parent directory does not allow write permission to the process.");
  422. return false;
  423. }
  424. return true;
  425. }
  426. bool removeAll(const FilePath& _filePath, Error* _err)
  427. {
  428. BX_ERROR_SCOPE(_err);
  429. if (remove(_filePath, _err) )
  430. {
  431. return true;
  432. }
  433. _err->reset();
  434. FileInfo fi;
  435. if (!stat(_filePath, fi) )
  436. {
  437. BX_ERROR_SET(_err, BX_ERROR_ACCESS, "The parent directory does not allow write permission to the process.");
  438. return false;
  439. }
  440. if (FileInfo::Directory != fi.m_type)
  441. {
  442. BX_ERROR_SET(_err, BX_ERROR_NOT_DIRECTORY, "File already exist, and is not directory.");
  443. return false;
  444. }
  445. #if BX_CRT_NONE
  446. BX_UNUSED(_filePath);
  447. return false;
  448. #elif BX_PLATFORM_WINDOWS \
  449. || BX_PLATFORM_LINUX \
  450. || BX_PLATFORM_OSX
  451. DIR* dir = opendir(_filePath.get() );
  452. if (NULL == dir)
  453. {
  454. BX_ERROR_SET(_err, BX_ERROR_NOT_DIRECTORY, "File already exist, and is not directory.");
  455. return false;
  456. }
  457. for (dirent* item = readdir(dir); NULL != item; item = readdir(dir) )
  458. {
  459. if (0 == strCmp(item->d_name, ".")
  460. || 0 == strCmp(item->d_name, "..") )
  461. {
  462. continue;
  463. }
  464. FilePath path(_filePath);
  465. path.join(item->d_name);
  466. if (!removeAll(path, _err) )
  467. {
  468. _err->reset();
  469. break;
  470. }
  471. }
  472. closedir(dir);
  473. #endif // !BX_CRT_NONE
  474. return remove(_filePath, _err);
  475. }
  476. } // namespace bx