filepath.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /*
  2. * Copyright 2010-2025 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bx/blob/master/LICENSE
  4. */
  5. #include <bx/file.h>
  6. #include <bx/os.h>
  7. #include <bx/readerwriter.h>
  8. #if BX_CRT_MSVC
  9. # include <direct.h> // _getcwd
  10. #else
  11. # include <unistd.h> // getcwd
  12. #endif // BX_CRT_MSVC
  13. #if BX_PLATFORM_WINDOWS
  14. #if !defined(GetModuleFileName)
  15. extern "C" __declspec(dllimport) unsigned long __stdcall GetModuleFileNameA(void* _module, char* _outFilePath, unsigned long _size);
  16. #endif
  17. extern "C" __declspec(dllimport) unsigned long __stdcall GetTempPathA(unsigned long _max, char* _outFilePath);
  18. #elif BX_PLATFORM_OSX
  19. extern "C" int _NSGetExecutablePath(char* _buf, uint32_t* _bufSize);
  20. #endif // BX_PLATFORM_WINDOWS
  21. namespace bx
  22. {
  23. static bool isPathSeparator(char _ch)
  24. {
  25. return false
  26. || '/' == _ch
  27. || '\\' == _ch
  28. ;
  29. }
  30. static int32_t normalizeFilePath(char* _dst, int32_t _dstSize, const char* _src, int32_t _num)
  31. {
  32. // Reference(s):
  33. // - 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. [[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(char* _out, uint32_t* _inOutSize, const StringView& _name, FileType::Enum _type)
  128. {
  129. uint32_t len = *_inOutSize;
  130. *_out = '\0';
  131. if (getEnv(_out, &len, _name) )
  132. {
  133. FileInfo fi;
  134. if (stat(fi, _out)
  135. && _type == fi.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_PLATFORM_*
  156. }
  157. static bool getCurrentPath(char* _out, uint32_t* _inOutSize)
  158. {
  159. uint32_t len = *_inOutSize;
  160. if (NULL != pwd(_out, len))
  161. {
  162. *_inOutSize = strLen(_out);
  163. return true;
  164. }
  165. return false;
  166. }
  167. static bool getExecutablePath(char* _out, uint32_t* _inOutSize)
  168. {
  169. #if BX_PLATFORM_WINDOWS
  170. uint32_t len = ::GetModuleFileNameA(NULL, _out, *_inOutSize);
  171. bool result = len != 0 && len < *_inOutSize;
  172. *_inOutSize = len;
  173. return result;
  174. #elif BX_PLATFORM_LINUX
  175. char tmp[64];
  176. snprintf(tmp, sizeof(tmp), "/proc/%d/exe", getpid() );
  177. ssize_t result = readlink(tmp, _out, *_inOutSize);
  178. if (-1 < result)
  179. {
  180. *_inOutSize = uint32_t(result);
  181. return true;
  182. }
  183. return false;
  184. #elif BX_PLATFORM_OSX
  185. uint32_t len = *_inOutSize;
  186. bool result = _NSGetExecutablePath(_out, &len);
  187. return 0 == result;
  188. #else
  189. BX_UNUSED(_out, _inOutSize);
  190. return false;
  191. #endif // BX_PLATFORM_*
  192. }
  193. static bool getHomePath(char* _out, uint32_t* _inOutSize)
  194. {
  195. return false
  196. #if BX_PLATFORM_WINDOWS
  197. || getEnv(_out, _inOutSize, "USERPROFILE", FileType::Dir)
  198. #endif // BX_PLATFORM_WINDOWS
  199. || getEnv(_out, _inOutSize, "HOME", FileType::Dir)
  200. ;
  201. }
  202. static bool getTempPath(char* _out, uint32_t* _inOutSize)
  203. {
  204. #if BX_PLATFORM_WINDOWS
  205. uint32_t len = ::GetTempPathA(*_inOutSize, _out);
  206. bool result = len != 0 && len < *_inOutSize;
  207. *_inOutSize = len;
  208. return result;
  209. #else
  210. static const StringView s_tmp[] =
  211. {
  212. "TMPDIR",
  213. "TMP",
  214. "TEMP",
  215. "TEMPDIR",
  216. ""
  217. };
  218. for (const StringView* tmp = s_tmp; !tmp->isEmpty(); ++tmp)
  219. {
  220. uint32_t len = *_inOutSize;
  221. *_out = '\0';
  222. bool ok = getEnv(_out, &len, *tmp, FileType::Dir);
  223. if (ok
  224. && len != 0
  225. && len < *_inOutSize)
  226. {
  227. *_inOutSize = len;
  228. return ok;
  229. }
  230. }
  231. FileInfo fi;
  232. if (stat(fi, "/tmp")
  233. && FileType::Dir == fi.type)
  234. {
  235. strCopy(_out, *_inOutSize, "/tmp");
  236. *_inOutSize = 4;
  237. return true;
  238. }
  239. return false;
  240. #endif // BX_PLATFORM_*
  241. }
  242. FilePath::FilePath()
  243. {
  244. set("");
  245. }
  246. FilePath::FilePath(Dir::Enum _dir)
  247. {
  248. set(_dir);
  249. }
  250. FilePath::FilePath(const char* _rhs)
  251. {
  252. set(_rhs);
  253. }
  254. FilePath::FilePath(const StringView& _filePath)
  255. {
  256. set(_filePath);
  257. }
  258. FilePath& FilePath::operator=(const StringView& _rhs)
  259. {
  260. set(_rhs);
  261. return *this;
  262. }
  263. void FilePath::clear()
  264. {
  265. if (!isEmpty() )
  266. {
  267. set("");
  268. }
  269. }
  270. void FilePath::set(Dir::Enum _dir)
  271. {
  272. bool ok = false;
  273. char tmp[kMaxFilePath];
  274. uint32_t len = BX_COUNTOF(tmp);
  275. switch (_dir)
  276. {
  277. case Dir::Current: ok = getCurrentPath(tmp, &len); break;
  278. case Dir::Executable: ok = getExecutablePath(tmp, &len); break;
  279. case Dir::Home: ok = getHomePath(tmp, &len); break;
  280. case Dir::Temp: ok = getTempPath(tmp, &len); break;
  281. default: break;
  282. }
  283. len = ok ? len : 0;
  284. set(StringView(tmp, len) );
  285. }
  286. void FilePath::set(const StringView& _filePath)
  287. {
  288. normalizeFilePath(
  289. m_filePath
  290. , BX_COUNTOF(m_filePath)
  291. , _filePath.getPtr()
  292. , _filePath.getLength()
  293. );
  294. }
  295. void FilePath::join(const StringView& _str)
  296. {
  297. char tmp[kMaxFilePath];
  298. strCopy(tmp, BX_COUNTOF(tmp), m_filePath);
  299. strCat(tmp, BX_COUNTOF(tmp), "/");
  300. strCat(tmp, BX_COUNTOF(tmp), _str);
  301. set(tmp);
  302. }
  303. FilePath::operator StringView() const
  304. {
  305. return StringView(m_filePath, strLen(m_filePath) );
  306. }
  307. const char* FilePath::getCPtr() const
  308. {
  309. return m_filePath;
  310. }
  311. StringView FilePath::getPath() const
  312. {
  313. StringView end = strRFind(m_filePath, '/');
  314. if (!end.isEmpty() )
  315. {
  316. return StringView(m_filePath, end.getPtr()+1);
  317. }
  318. return StringView();
  319. }
  320. StringView FilePath::getFileName() const
  321. {
  322. StringView fileName = strRFind(m_filePath, '/');
  323. if (!fileName.isEmpty() )
  324. {
  325. return StringView(fileName.getPtr()+1);
  326. }
  327. return getCPtr();
  328. }
  329. StringView FilePath::getBaseName() const
  330. {
  331. const StringView fileName = getFileName();
  332. if (!fileName.isEmpty() )
  333. {
  334. StringView ext = strFind(fileName, '.');
  335. if (!ext.isEmpty() )
  336. {
  337. return StringView(fileName.getPtr(), ext.getPtr() );
  338. }
  339. return fileName;
  340. }
  341. return StringView();
  342. }
  343. StringView FilePath::getExt() const
  344. {
  345. const StringView fileName = getFileName();
  346. if (!fileName.isEmpty() )
  347. {
  348. const StringView dot = strFind(fileName, '.');
  349. return StringView(dot.getPtr(), fileName.getTerm() );
  350. }
  351. return StringView();
  352. }
  353. bool FilePath::isAbsolute() const
  354. {
  355. return '/' == m_filePath[0] // no drive letter
  356. || (':' == m_filePath[1] && '/' == m_filePath[2]) // with drive letter
  357. ;
  358. }
  359. bool FilePath::isEmpty() const
  360. {
  361. return 0 == strCmp(m_filePath, ".");
  362. }
  363. } // namespace bx