filepath.cpp 10.0 KB

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