fileSystemFunctions.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "console/console.h"
  24. #include "console/consoleInternal.h"
  25. #include "console/engineAPI.h"
  26. #include "core/stream/fileStream.h"
  27. #include "platform/platformInput.h"
  28. #include "torqueConfig.h"
  29. #include "core/frameAllocator.h"
  30. // Buffer for expanding script filenames.
  31. static char sgScriptFilenameBuffer[1024];
  32. //-------------------------------------- Helper Functions
  33. static void forwardslash(char *str)
  34. {
  35. while(*str)
  36. {
  37. if(*str == '\\')
  38. *str = '/';
  39. str++;
  40. }
  41. }
  42. //----------------------------------------------------------------
  43. static Vector<String> sgFindFilesResults;
  44. static U32 sgFindFilesPos = 0;
  45. static S32 buildFileList(const char* pattern, bool recurse, bool multiMatch)
  46. {
  47. static const String sSlash( "/" );
  48. sgFindFilesResults.clear();
  49. String sPattern(Torque::Path::CleanSeparators(pattern));
  50. if(sPattern.isEmpty())
  51. {
  52. Con::errorf("findFirstFile() requires a search pattern");
  53. return -1;
  54. }
  55. if(!Con::expandScriptFilename(sgScriptFilenameBuffer, sizeof(sgScriptFilenameBuffer), sPattern.c_str()))
  56. {
  57. Con::errorf("findFirstFile() given initial directory cannot be expanded: '%s'", pattern);
  58. return -1;
  59. }
  60. sPattern = String::ToString(sgScriptFilenameBuffer);
  61. String::SizeType slashPos = sPattern.find('/', 0, String::Right);
  62. // if(slashPos == String::NPos)
  63. // {
  64. // Con::errorf("findFirstFile() missing search directory or expression: '%s'", sPattern.c_str());
  65. // return -1;
  66. // }
  67. // Build the initial search path
  68. Torque::Path givenPath(Torque::Path::CompressPath(sPattern));
  69. givenPath.setFileName("*");
  70. givenPath.setExtension("*");
  71. if(givenPath.getPath().length() > 0 && givenPath.getPath().find('*', 0, String::Right) == givenPath.getPath().length()-1)
  72. {
  73. // Deal with legacy searches of the form '*/*.*'
  74. String suspectPath = givenPath.getPath();
  75. String::SizeType newLen = suspectPath.length()-1;
  76. if(newLen > 0 && suspectPath.find('/', 0, String::Right) == suspectPath.length()-2)
  77. {
  78. --newLen;
  79. }
  80. givenPath.setPath(suspectPath.substr(0, newLen));
  81. }
  82. Torque::FS::FileSystemRef fs = Torque::FS::GetFileSystem(givenPath);
  83. //Torque::Path path = fs->mapTo(givenPath);
  84. Torque::Path path = givenPath;
  85. // Make sure that we have a root so the correct file system can be determined when using zips
  86. if(givenPath.isRelative())
  87. path = Torque::Path::Join(Torque::FS::GetCwd(), '/', givenPath);
  88. path.setFileName(String::EmptyString);
  89. path.setExtension(String::EmptyString);
  90. if(!Torque::FS::IsDirectory(path))
  91. {
  92. Con::errorf("findFirstFile() invalid initial search directory: '%s'", path.getFullPath().c_str());
  93. return -1;
  94. }
  95. // Build the search expression
  96. const String expression(slashPos != String::NPos ? sPattern.substr(slashPos+1) : sPattern);
  97. if(expression.isEmpty())
  98. {
  99. Con::errorf("findFirstFile() requires a search expression: '%s'", sPattern.c_str());
  100. return -1;
  101. }
  102. S32 results = Torque::FS::FindByPattern(path, expression, recurse, sgFindFilesResults, multiMatch );
  103. if(givenPath.isRelative() && results > 0)
  104. {
  105. // Strip the CWD out of the returned paths
  106. // MakeRelativePath() returns incorrect results (it adds a leading ..) so doing this the dirty way
  107. const String cwd = Torque::FS::GetCwd().getFullPath();
  108. for(S32 i = 0;i < sgFindFilesResults.size();++i)
  109. {
  110. String str = sgFindFilesResults[i];
  111. if(str.compare(cwd, cwd.length(), String::NoCase) == 0)
  112. str = str.substr(cwd.length());
  113. sgFindFilesResults[i] = str;
  114. }
  115. }
  116. return results;
  117. }
  118. //-----------------------------------------------------------------------------
  119. DefineEngineFunction( findFirstFile, String, ( const char* pattern, bool recurse ), ( "", true ),
  120. "@brief Returns the first file in the directory system matching the given pattern.\n\n"
  121. "Use the corresponding findNextFile() to step through "
  122. "the results. If you're only interested in the number of files returned by the "
  123. "pattern match, use getFileCount().\n\n"
  124. "This function differs from findFirstFileMultiExpr() in that it supports a single search "
  125. "pattern being passed in.\n\n"
  126. "@note You cannot run multiple simultaneous file system searches with these functions. Each "
  127. "call to findFirstFile() and findFirstFileMultiExpr() initiates a new search and renders "
  128. "a previous search invalid.\n\n"
  129. "@param pattern The path and file name pattern to match against.\n"
  130. "@param recurse If true, the search will exhaustively recurse into subdirectories of the given path and match the given filename pattern.\n"
  131. "@return The path of the first file matched by the search or an empty string if no matching file could be found.\n\n"
  132. "@tsexample\n"
  133. "// Execute all ." TORQUE_SCRIPT_EXTENSION " files in a subdirectory and its subdirectories.\n"
  134. "for( %file = findFirstFile( \"subdirectory/*." TORQUE_SCRIPT_EXTENSION "\" ); %file !$= \"\"; %file = findNextFile() )\n"
  135. " exec( %file );\n"
  136. "@endtsexample\n\n"
  137. "@see findNextFile()"
  138. "@see getFileCount()"
  139. "@see findFirstFileMultiExpr()"
  140. "@ingroup FileSearches" )
  141. {
  142. S32 numResults = buildFileList( pattern, recurse, false);
  143. // For Debugging
  144. //for ( S32 i = 0; i < sgFindFilesResults.size(); i++ )
  145. // Con::printf( " [%i] [%s]", i, sgFindFilesResults[i].c_str() );
  146. sgFindFilesPos = 1;
  147. if(numResults < 0)
  148. {
  149. Con::errorf("findFirstFile() search directory not found: '%s'", pattern);
  150. return String();
  151. }
  152. return numResults ? sgFindFilesResults[0] : String();
  153. }
  154. //-----------------------------------------------------------------------------
  155. DefineEngineFunction( findNextFile, String, ( const char* pattern ), ( "" ),
  156. "@brief Returns the next file matching a search begun in findFirstFile().\n\n"
  157. "@param pattern The path and file name pattern to match against. This is optional "
  158. "and may be left out as it is not used by the code. It is here for legacy reasons.\n"
  159. "@return The path of the next filename matched by the search or an empty string if no more files match.\n\n"
  160. "@tsexample\n"
  161. "// Execute all ." TORQUE_SCRIPT_EXTENSION " files in a subdirectory and its subdirectories.\n"
  162. "for( %file = findFirstFile( \"subdirectory/*." TORQUE_SCRIPT_EXTENSION "\" ); %file !$= \"\"; %file = findNextFile() )\n"
  163. " exec( %file );\n"
  164. "@endtsexample\n\n"
  165. "@see findFirstFile()"
  166. "@ingroup FileSearches" )
  167. {
  168. if ( sgFindFilesPos + 1 > sgFindFilesResults.size() )
  169. return String();
  170. return sgFindFilesResults[sgFindFilesPos++];
  171. }
  172. //-----------------------------------------------------------------------------
  173. DefineEngineFunction( getFileCount, S32, ( const char* pattern, bool recurse ), ( "", true ),
  174. "@brief Returns the number of files in the directory tree that match the given patterns\n\n"
  175. "This function differs from getFileCountMultiExpr() in that it supports a single search "
  176. "pattern being passed in.\n\n"
  177. "If you're interested in a list of files that match the given pattern and not just "
  178. "the number of files, use findFirstFile() and findNextFile().\n\n"
  179. "@param pattern The path and file name pattern to match against.\n"
  180. "@param recurse If true, the search will exhaustively recurse into subdirectories of the given path and match the given filename pattern "
  181. "counting files in subdirectories.\n"
  182. "@return Number of files located using the pattern\n\n"
  183. "@tsexample\n"
  184. "// Count the number of ." TORQUE_SCRIPT_EXTENSION " files in a subdirectory and its subdirectories.\n"
  185. "getFileCount( \"subdirectory/*." TORQUE_SCRIPT_EXTENSION "\" );\n"
  186. "@endtsexample\n\n"
  187. "@see findFirstFile()"
  188. "@see findNextFile()"
  189. "@see getFileCountMultiExpr()"
  190. "@ingroup FileSearches" )
  191. {
  192. S32 numResults = buildFileList( pattern, recurse, false );
  193. if(numResults < 0)
  194. {
  195. return 0;
  196. }
  197. return numResults;
  198. }
  199. //-----------------------------------------------------------------------------
  200. DefineEngineFunction(findFirstFileMultiExpr, String, ( const char* pattern, bool recurse ), ( "", true),
  201. "@brief Returns the first file in the directory system matching the given patterns.\n\n"
  202. "Use the corresponding findNextFileMultiExpr() to step through "
  203. "the results. If you're only interested in the number of files returned by the "
  204. "pattern match, use getFileCountMultiExpr().\n\n"
  205. "This function differs from findFirstFile() in that it supports multiple search patterns "
  206. "to be passed in.\n\n"
  207. "@note You cannot run multiple simultaneous file system searches with these functions. Each "
  208. "call to findFirstFile() and findFirstFileMultiExpr() initiates a new search and renders "
  209. "a previous search invalid.\n\n"
  210. "@param pattern The path and file name pattern to match against, such as *." TORQUE_SCRIPT_EXTENSION ". Separate "
  211. "multiple patterns with TABs. For example: \"*." TORQUE_SCRIPT_EXTENSION "\" TAB \"*.dso\"\n"
  212. "@param recurse If true, the search will exhaustively recurse into subdirectories "
  213. "of the given path and match the given filename patterns.\n"
  214. "@return String of the first matching file path, or an empty string if no matching "
  215. "files were found.\n\n"
  216. "@tsexample\n"
  217. "// Find all DTS or Collada models\n"
  218. "%filePatterns = \"*.dts\" TAB \"*.dae\";\n"
  219. "%fullPath = findFirstFileMultiExpr( %filePatterns );\n"
  220. "while ( %fullPath !$= \"\" )\n"
  221. "{\n"
  222. " echo( %fullPath );\n"
  223. " %fullPath = findNextFileMultiExpr( %filePatterns );\n"
  224. "}\n"
  225. "@endtsexample\n\n"
  226. "@see findNextFileMultiExpr()"
  227. "@see getFileCountMultiExpr()"
  228. "@see findFirstFile()"
  229. "@ingroup FileSearches")
  230. {
  231. S32 numResults = buildFileList(pattern, recurse, true);
  232. // For Debugging
  233. //for ( S32 i = 0; i < sgFindFilesResults.size(); i++ )
  234. // Con::printf( " [%i] [%s]", i, sgFindFilesResults[i].c_str() );
  235. sgFindFilesPos = 1;
  236. if(numResults < 0)
  237. {
  238. Con::errorf("findFirstFileMultiExpr() search directory not found: '%s'", pattern);
  239. return String();
  240. }
  241. return numResults ? sgFindFilesResults[0] : String();
  242. }
  243. DefineEngineFunction(findNextFileMultiExpr, String, ( const char* pattern ), (""),
  244. "@brief Returns the next file matching a search begun in findFirstFileMultiExpr().\n\n"
  245. "@param pattern The path and file name pattern to match against. This is optional "
  246. "and may be left out as it is not used by the code. It is here for legacy reasons.\n"
  247. "@return String of the next matching file path, or an empty string if no matching "
  248. "files were found.\n\n"
  249. "@tsexample\n"
  250. "// Find all DTS or Collada models\n"
  251. "%filePatterns = \"*.dts\" TAB \"*.dae\";\n"
  252. "%fullPath = findFirstFileMultiExpr( %filePatterns );\n"
  253. "while ( %fullPath !$= \"\" )\n"
  254. "{\n"
  255. " echo( %fullPath );\n"
  256. " %fullPath = findNextFileMultiExpr( %filePatterns );\n"
  257. "}\n"
  258. "@endtsexample\n\n"
  259. "@see findFirstFileMultiExpr()"
  260. "@ingroup FileSearches")
  261. {
  262. if ( sgFindFilesPos + 1 > sgFindFilesResults.size() )
  263. return String();
  264. return sgFindFilesResults[sgFindFilesPos++];
  265. }
  266. DefineEngineFunction(getFileCountMultiExpr, S32, ( const char* pattern, bool recurse ), ( "", true),
  267. "@brief Returns the number of files in the directory tree that match the given patterns\n\n"
  268. "If you're interested in a list of files that match the given patterns and not just "
  269. "the number of files, use findFirstFileMultiExpr() and findNextFileMultiExpr().\n\n"
  270. "@param pattern The path and file name pattern to match against, such as *." TORQUE_SCRIPT_EXTENSION ". Separate "
  271. "multiple patterns with TABs. For example: \"*." TORQUE_SCRIPT_EXTENSION "\" TAB \"*.dso\"\n"
  272. "@param recurse If true, the search will exhaustively recurse into subdirectories "
  273. "of the given path and match the given filename pattern.\n"
  274. "@return Number of files located using the patterns\n\n"
  275. "@tsexample\n"
  276. "// Count all DTS or Collada models\n"
  277. "%filePatterns = \"*.dts\" TAB \"*.dae\";\n"
  278. "echo( \"Nunmer of shape files:\" SPC getFileCountMultiExpr( %filePatterns ) );\n"
  279. "@endtsexample\n\n"
  280. "@see findFirstFileMultiExpr()"
  281. "@see findNextFileMultiExpr()"
  282. "@ingroup FileSearches")
  283. {
  284. S32 numResults = buildFileList(pattern, recurse, true);
  285. if(numResults < 0)
  286. {
  287. return 0;
  288. }
  289. return numResults;
  290. }
  291. DefineEngineFunction(getFileCRC, S32, ( const char* fileName ),,
  292. "@brief Provides the CRC checksum of the given file.\n\n"
  293. "@param fileName The path to the file.\n"
  294. "@return The calculated CRC checksum of the file, or -1 if the file "
  295. "could not be found.\n"
  296. "@ingroup FileSystem")
  297. {
  298. Torque::FS::FileNodeRef fileRef = Torque::FS::GetFileNode( fileName );
  299. if ( fileRef == NULL )
  300. {
  301. Con::errorf("getFileCRC() - could not access file: [%s]", fileName );
  302. return -1;
  303. }
  304. return fileRef->getChecksum();
  305. }
  306. DefineEngineFunction(isFile, bool, ( const char* fileName ),,
  307. "@brief Determines if the specified file exists or not\n\n"
  308. "@param fileName The path to the file.\n"
  309. "@return Returns true if the file was found.\n"
  310. "@ingroup FileSystem")
  311. {
  312. String cleanfilename(Torque::Path::CleanSeparators(fileName));
  313. Con::expandScriptFilename(sgScriptFilenameBuffer, sizeof(sgScriptFilenameBuffer), cleanfilename.c_str());
  314. Torque::Path givenPath(Torque::Path::CompressPath(sgScriptFilenameBuffer));
  315. if (givenPath.getFileName().isEmpty() && givenPath.getExtension().isNotEmpty())
  316. {
  317. //specially named or hidden files, like .gitignore parse incorrectly due to having
  318. //"no" filename, so we adjust that
  319. givenPath.setFileName(String(".") + givenPath.getExtension());
  320. givenPath.setExtension("");
  321. }
  322. if (Torque::FS::IsFile(givenPath)) return true;
  323. //try with script file extension
  324. if (!Torque::FS::IsFile(givenPath) && givenPath.getExtension().isEmpty())
  325. givenPath.setExtension(TORQUE_SCRIPT_EXTENSION);
  326. if (Torque::FS::IsFile(givenPath)) return true;
  327. //finally, try with compiled script file extension
  328. if (!Torque::FS::IsFile(givenPath))
  329. givenPath.setExtension(String(TORQUE_SCRIPT_EXTENSION)+String(".dso"));
  330. return Torque::FS::IsFile(givenPath);
  331. }
  332. DefineEngineFunction(isScriptFile, bool, (const char* fileName), ,
  333. "@brief Determines if the specified file exists or not\n\n"
  334. "@param fileName The path to the file.\n"
  335. "@return Returns true if the file was found.\n"
  336. "@ingroup FileSystem")
  337. {
  338. return Con::isScriptFile(fileName);
  339. }
  340. DefineEngineFunction( IsDirectory, bool, ( const char* directory ),,
  341. "@brief Determines if a specified directory exists or not\n\n"
  342. "@param directory String containing path in the form of \"foo/bar\"\n"
  343. "@return Returns true if the directory was found.\n"
  344. "@note Do not include a trailing slash '/'.\n"
  345. "@ingroup FileSystem")
  346. {
  347. return Torque::FS::IsDirectory( directory );
  348. }
  349. DefineEngineFunction(isWriteableFileName, bool, ( const char* fileName ),,
  350. "@brief Determines if a file name can be written to using File I/O\n\n"
  351. "@param fileName Name and path of file to check\n"
  352. "@return Returns true if the file can be written to.\n"
  353. "@ingroup FileSystem")
  354. {
  355. return !Torque::FS::IsReadOnly(fileName);
  356. }
  357. DefineEngineFunction(startFileChangeNotifications, void, (),,
  358. "@brief Start watching resources for file changes\n\n"
  359. "Typically this is called during initializeCore().\n\n"
  360. "@see stopFileChangeNotifications()\n"
  361. "@ingroup FileSystem")
  362. {
  363. Torque::FS::StartFileChangeNotifications();
  364. }
  365. DefineEngineFunction(stopFileChangeNotifications, void, (),,
  366. "@brief Stop watching resources for file changes\n\n"
  367. "Typically this is called during shutdownCore().\n\n"
  368. "@see startFileChangeNotifications()\n"
  369. "@ingroup FileSystem")
  370. {
  371. Torque::FS::StopFileChangeNotifications();
  372. }
  373. DefineEngineFunction(getDirectoryList, String, ( const char* path, S32 depth ), ( "", 0 ),
  374. "@brief Gathers a list of directories starting at the given path.\n\n"
  375. "@param path String containing the path of the directory\n"
  376. "@param depth Depth of search, as in how many subdirectories to parse through\n"
  377. "@return Tab delimited string containing list of directories found during search, \"\" if no files were found\n"
  378. "@ingroup FileSystem")
  379. {
  380. // Grab the full path.
  381. char fullpath[1024];
  382. #ifdef TORQUE_SECURE_VFS
  383. dStrcpy(fullpath, path, sizeof(fullpath));
  384. #else
  385. Platform::makeFullPathName(String::compare(path, "/") == 0 ? "" : path, fullpath, sizeof(fullpath));
  386. #endif
  387. //dSprintf(fullpath, 511, "%s/%s", Platform::getWorkingDirectory(), path);
  388. // Append a trailing backslash if it's not present already.
  389. if (fullpath[dStrlen(fullpath) - 1] != '/')
  390. {
  391. dStrcat(fullpath, "/\0", 1024);
  392. }
  393. // Dump the directories.
  394. Vector<StringTableEntry> directories;
  395. Torque::FS::DumpDirectories(fullpath, directories, depth, true);
  396. if( directories.empty() )
  397. return "";
  398. // Grab the required buffer length.
  399. S32 length = 0;
  400. for (S32 i = 0; i < directories.size(); i++)
  401. length += dStrlen(directories[i]) + 1;
  402. // Get a return buffer.
  403. char* buffer = Con::getReturnBuffer(length);
  404. char* p = buffer;
  405. // Copy the directory names to the buffer.
  406. for (S32 i = 0; i < directories.size(); i++)
  407. {
  408. dStrcpy(p, directories[i], length - (p - buffer));
  409. p += dStrlen(directories[i]);
  410. // Tab separated.
  411. p[0] = '\t';
  412. p++;
  413. }
  414. p--;
  415. p[0] = '\0';
  416. return buffer;
  417. }
  418. DefineEngineFunction(fileSize, S32, ( const char* fileName ),,
  419. "@brief Determines the size of a file on disk\n\n"
  420. "@param fileName Name and path of the file to check\n"
  421. "@return Returns filesize in bytes, or -1 if no file\n"
  422. "@ingroup FileSystem")
  423. {
  424. StrongRefPtr<Torque::FS::FileNode> node = Torque::FS::GetFileNode(fileName);
  425. if (node.isValid())
  426. {
  427. return node->getSize();
  428. }
  429. return -1;
  430. }
  431. DefineEngineFunction( fileModifiedTime, String, ( const char* fileName ),,
  432. "@brief Returns a platform specific formatted string with the last modified time for the file.\n\n"
  433. "@param fileName Name and path of file to check\n"
  434. "@return Formatted string (OS specific) containing modified time, \"9/3/2010 12:33:47 PM\" for example\n"
  435. "@ingroup FileSystem")
  436. {
  437. Torque::FS::FileNodeRef node = Torque::FS::GetFileNode(fileName);
  438. if (node)
  439. {
  440. Platform::LocalTime lt = node->getModifiedTime().toLocalTime();
  441. String fileStr = Platform::localTimeToString(lt);
  442. char *buffer = Con::getReturnBuffer(fileStr.size());
  443. dStrcpy(buffer, fileStr, fileStr.size());
  444. return buffer;
  445. }
  446. return "";
  447. }
  448. DefineEngineFunction( fileCreatedTime, String, ( const char* fileName ),,
  449. "@brief Returns a platform specific formatted string with the creation time for the file."
  450. "@param fileName Name and path of file to check\n"
  451. "@return Formatted string (OS specific) containing created time, \"9/3/2010 12:33:47 PM\" for example\n"
  452. "@ingroup FileSystem")
  453. {
  454. Torque::FS::FileNodeRef node = Torque::FS::GetFileNode(fileName);
  455. if (node)
  456. {
  457. Platform::LocalTime lt = node->getCreatedTime().toLocalTime();
  458. String fileStr = Platform::localTimeToString(lt);
  459. char *buffer = Con::getReturnBuffer(fileStr.size());
  460. dStrcpy(buffer, fileStr, fileStr.size());
  461. return buffer;
  462. }
  463. return "";
  464. }
  465. DefineEngineFunction(compareFileTimes, S32, (const char* fileA, const char* fileB), ("", ""),
  466. "@brief Compares 2 files' modified file times."
  467. "@param fileName Name and path of first file to compare\n"
  468. "@param fileName Name and path of second file to compare\n"
  469. "@return S32. If value is 1, then fileA is newer. If value is -1, then fileB is newer. If value is 0, they are equal.\n"
  470. "@ingroup FileSystem")
  471. {
  472. Torque::FS::FileNodeRef nodeA = Torque::FS::GetFileNode(fileA);
  473. Torque::FS::FileNodeRef nodeB = Torque::FS::GetFileNode(fileB);
  474. // Can't do anything if either file doesn't exist
  475. if (!nodeA || !nodeB)
  476. {
  477. return 0;
  478. }
  479. Torque::FS::FileNode::Attributes fileAAttributes;
  480. Torque::FS::FileNode::Attributes fileBAttributes;
  481. // If retrieval of attributes fails, we can't compare
  482. if (!nodeA->getAttributes(&fileAAttributes) || !nodeB->getAttributes(&fileBAttributes))
  483. {
  484. return 0;
  485. }
  486. if (fileAAttributes.mtime > fileBAttributes.mtime)
  487. {
  488. return 1;
  489. }
  490. else if (fileAAttributes.mtime < fileBAttributes.mtime)
  491. {
  492. return -1;
  493. }
  494. return 0;
  495. }
  496. DefineEngineFunction(fileDelete, bool, ( const char* path ),,
  497. "@brief Delete a file from the hard drive\n\n"
  498. "@param path Name and path of the file to delete\n"
  499. "@note THERE IS NO RECOVERY FROM THIS. Deleted file is gone for good.\n"
  500. "@return True if file was successfully deleted\n"
  501. "@ingroup FileSystem")
  502. {
  503. return Torque::FS::Remove(path);
  504. }
  505. //----------------------------------------------------------------
  506. DefineEngineFunction(fileExt, String, ( const char* fileName ),,
  507. "@brief Get the extension of a file\n\n"
  508. "@param fileName Name and path of file\n"
  509. "@return String containing the extension, such as \".exe\" or \"." TORQUE_SCRIPT_EXTENSION "\"\n"
  510. "@ingroup FileSystem")
  511. {
  512. const char *ret = dStrrchr(fileName, '.');
  513. if(ret)
  514. return ret;
  515. return "";
  516. }
  517. DefineEngineFunction(fileBase, String, ( const char* fileName ),,
  518. "@brief Get the base of a file name (removes extension and path)\n\n"
  519. "@param fileName Name and path of file to check\n"
  520. "@return String containing the file name, minus extension and path\n"
  521. "@ingroup FileSystem")
  522. {
  523. S32 pathLen = dStrlen( fileName );
  524. FrameTemp<char> szPathCopy( pathLen + 1);
  525. dStrcpy( szPathCopy, fileName, pathLen + 1 );
  526. forwardslash( szPathCopy );
  527. const char *path = dStrrchr(szPathCopy, '/');
  528. if(!path)
  529. path = szPathCopy;
  530. else
  531. path++;
  532. dsize_t retLen = dStrlen(path) + 1;
  533. char *ret = Con::getReturnBuffer(retLen);
  534. dStrcpy(ret, path, retLen);
  535. char *ext = dStrrchr(ret, '.');
  536. if(ext)
  537. *ext = 0;
  538. return ret;
  539. }
  540. DefineEngineFunction(fileName, String, ( const char* fileName ),,
  541. "@brief Get only the file name of a path and file name string (removes path)\n\n"
  542. "@param fileName Name and path of file to check\n"
  543. "@return String containing the file name, minus the path\n"
  544. "@ingroup FileSystem")
  545. {
  546. S32 pathLen = dStrlen( fileName );
  547. FrameTemp<char> szPathCopy( pathLen + 1);
  548. dStrcpy( szPathCopy, fileName, pathLen + 1 );
  549. forwardslash( szPathCopy );
  550. const char *name = dStrrchr(szPathCopy, '/');
  551. if(!name)
  552. name = szPathCopy;
  553. else
  554. name++;
  555. dsize_t retLen = dStrlen(name) + 1;
  556. char *ret = Con::getReturnBuffer(retLen);
  557. dStrcpy(ret, name, retLen);
  558. return ret;
  559. }
  560. DefineEngineFunction(filePath, String, ( const char* fileName ),,
  561. "@brief Get the path of a file (removes name and extension)\n\n"
  562. "@param fileName Name and path of file to check\n"
  563. "@return String containing the path, minus name and extension\n"
  564. "@ingroup FileSystem")
  565. {
  566. S32 pathLen = dStrlen( fileName );
  567. FrameTemp<char> szPathCopy( pathLen + 1);
  568. dStrcpy( szPathCopy, fileName, pathLen + 1 );
  569. forwardslash( szPathCopy );
  570. const char *path = dStrrchr(szPathCopy, '/');
  571. if(!path)
  572. return "";
  573. U32 len = path - (char*)szPathCopy;
  574. char *ret = Con::getReturnBuffer(len + 1);
  575. dStrncpy(ret, szPathCopy, len);
  576. ret[len] = 0;
  577. return ret;
  578. }
  579. DefineEngineFunction(getWorkingDirectory, String, (),,
  580. "@brief Reports the current directory\n\n"
  581. "@return String containing full file path of working directory\n"
  582. "@ingroup FileSystem")
  583. {
  584. return Platform::getCurrentDirectory();
  585. }
  586. //-----------------------------------------------------------------------------
  587. // [tom, 5/1/2007] I changed these to be ordinary console functions as they
  588. // are just string processing functions. They are needed by the 3D tools which
  589. // are not currently built with TORQUE_TOOLS defined.
  590. DefineEngineFunction(makeFullPath, String, ( const char* path, const char* cwd ), ( "", ""),
  591. "@brief Converts a relative file path to a full path\n\n"
  592. "For example, \"./console.log\" becomes \"C:/Torque/t3d/examples/FPS Example/game/console.log\"\n"
  593. "@param path Name of file or path to check\n"
  594. "@param cwd Optional current working directory from which to build the full path.\n"
  595. "@return String containing non-relative directory of path\n"
  596. "@ingroup FileSystem")
  597. {
  598. static const U32 bufSize = 512;
  599. char *buf = Con::getReturnBuffer(bufSize);
  600. Platform::makeFullPathName(path, buf, bufSize, dStrlen(cwd) > 1 ? cwd : NULL);
  601. return buf;
  602. }
  603. DefineEngineFunction(makeRelativePath, String, ( const char* path, const char* to ), ( "", ""),
  604. "@brief Turns a full or local path to a relative one\n\n"
  605. "For example, \"./game/art\" becomes \"game/art\"\n"
  606. "@param path Full path (may include a file) to convert\n"
  607. "@param to Optional base path used for the conversion. If not supplied the current "
  608. "working directory is used.\n"
  609. "@returns String containing relative path\n"
  610. "@ingroup FileSystem")
  611. {
  612. return Platform::makeRelativePathName( path, dStrlen(to) > 1 ? to : NULL );
  613. }
  614. DefineEngineFunction(pathConcat, String, ( const char* path, const char* file), ( "", ""),
  615. "@brief Combines two separate strings containing a file path and file name together into a single string\n\n"
  616. "@param path String containing file path\n"
  617. "@param file String containing file name\n"
  618. "@return String containing concatenated file name and path\n"
  619. "@ingroup FileSystem")
  620. {
  621. static const U32 bufSize = 1024;
  622. char *buf = Con::getReturnBuffer(bufSize);
  623. Platform::makeFullPathName(file, buf, bufSize, path);
  624. return buf;
  625. }
  626. //-----------------------------------------------------------------------------
  627. DefineEngineFunction(getExecutableName, String, (),,
  628. "@brief Gets the name of the game's executable\n\n"
  629. "@return String containing this game's executable name\n"
  630. "@ingroup FileSystem")
  631. {
  632. return Platform::getExecutableName();
  633. }
  634. //-----------------------------------------------------------------------------
  635. DefineEngineFunction( getMainDotCsDir, String, (),,
  636. "@brief Get the absolute path to the directory that contains the main." TORQUE_SCRIPT_EXTENSION " script from which the engine was started.\n\n"
  637. "This directory will usually contain all the game assets and, in a user-side game installation, will usually be "
  638. "read-only.\n\n"
  639. "@return The path to the main game assets.\n\n"
  640. "@ingroup FileSystem\n")
  641. {
  642. return Platform::getMainDotCsDir();
  643. }
  644. //-----------------------------------------------------------------------------
  645. // Tools Only Functions
  646. //-----------------------------------------------------------------------------
  647. #ifdef TORQUE_TOOLS
  648. //-----------------------------------------------------------------------------
  649. DefineEngineFunction( openFolder, void, ( const char* path ),,
  650. "@brief Open the given folder in the system's file manager.\n\n"
  651. "@param path full path to a directory.\n\n"
  652. "@note Only present in a Tools build of Torque.\n"
  653. "@ingroup FileSystem\n")
  654. {
  655. Platform::openFolder( path );
  656. }
  657. //-----------------------------------------------------------------------------
  658. DefineEngineFunction( openFile, void, ( const char* file ),,
  659. "@brief Open the given @a file through the system. This will usually open the file in its "
  660. "associated application.\n"
  661. "@param file %Path of the file to open.\n\n"
  662. "@note Only present in a Tools build of Torque.\n"
  663. "@ingroup FileSystem\n")
  664. {
  665. Platform::openFile( file );
  666. }
  667. //-----------------------------------------------------------------------------
  668. DefineEngineFunction( pathCopy, bool, ( const char* fromFile, const char* toFile, bool noOverwrite ), ( "", "", true ),
  669. "@brief Copy a file to a new location.\n"
  670. "@param fromFile %Path of the file to copy.\n"
  671. "@param toFile %Path where to copy @a fromFile to.\n"
  672. "@param noOverwrite If true, then @a fromFile will not overwrite a file that may already exist at @a toFile.\n"
  673. "@return True if the file was successfully copied, false otherwise.\n"
  674. "@note Only present in a Tools build of Torque.\n"
  675. "@ingroup FileSystem")
  676. {
  677. return Torque::FS::CopyFile(fromFile, toFile, noOverwrite);
  678. }
  679. //-----------------------------------------------------------------------------
  680. DefineEngineFunction( getCurrentDirectory, String, (),,
  681. "@brief Return the current working directory.\n\n"
  682. "@return The absolute path of the current working directory.\n\n"
  683. "@note Only present in a Tools build of Torque.\n"
  684. "@see getWorkingDirectory()"
  685. "@ingroup FileSystem")
  686. {
  687. #ifdef TORQUE_SECURE_VFS
  688. return Torque::FS::GetCwd();
  689. #else
  690. return Platform::getCurrentDirectory();
  691. #endif
  692. }
  693. //-----------------------------------------------------------------------------
  694. DefineEngineFunction( setCurrentDirectory, bool, ( const char* path ),,
  695. "@brief Set the current working directory.\n\n"
  696. "@param path The absolute or relative (to the current working directory) path of the directory which should be made the new "
  697. "working directory.\n\n"
  698. "@return True if the working directory was successfully changed to @a path, false otherwise.\n\n"
  699. "@note Only present in a Tools build of Torque.\n"
  700. "@ingroup FileSystem")
  701. {
  702. #ifdef TORQUE_SECURE_VFS
  703. return Torque::FS::SetCwd(path);
  704. #else
  705. return Platform::setCurrentDirectory( StringTable->insert( path ) );
  706. #endif
  707. }
  708. //-----------------------------------------------------------------------------
  709. DefineEngineFunction( createPath, bool, ( const char* path ),,
  710. "@brief Create the given directory or the path leading to the given filename.\n\n"
  711. "If @a path ends in a trailing slash, then all components in the given path will be created as directories (if not already in place). If @a path, "
  712. "does @b not end in a trailing slash, then the last component of the path is taken to be a file name and only the directory components "
  713. "of the path will be created.\n\n"
  714. "@param path The path to create.\n\n"
  715. "@note Only present in a Tools build of Torque.\n"
  716. "@ingroup FileSystem" )
  717. {
  718. return Torque::FS::CreatePath(path);
  719. }
  720. DefineEngineFunction(deleteDirectory, bool, (const char* path), ,
  721. "@brief Delete a directory from the hard drive\n\n"
  722. "@param path Name and path of the folder to delete\n"
  723. "@note THERE IS NO RECOVERY FROM THIS. Deleted files are gone for good.\n"
  724. "@return True if file was successfully deleted\n"
  725. "@ingroup FileSystem")
  726. {
  727. static char fileName[1024];
  728. static char sandboxFileName[1024];
  729. Con::expandScriptFilename(fileName, sizeof(fileName), path);
  730. Platform::makeFullPathName(fileName, sandboxFileName, sizeof(sandboxFileName));
  731. return Platform::deleteDirectory(sandboxFileName);
  732. }
  733. #endif // TORQUE_TOOLS