main.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. 
  2. // A program for cloning a project from one folder to another, while updating relative paths to headers outside of the folder.
  3. // TODO:
  4. // * Give a warning when the source and target paths are on different drives, because absolute paths do not work across different operating systems.
  5. // * Create a visual interface for creating new projects from templates in the Wizard application.
  6. // Choose to create a new project, choose a template, choose a new name and location.
  7. // * Filter out files using patterns, to avoid cloning executable files and descriptions of template projects.
  8. #include "../../../DFPSR/includeEssentials.h"
  9. using namespace dsr;
  10. struct FileConversion {
  11. String sourceFilePath;
  12. String targetFilePath;
  13. FileConversion(const ReadableString &sourceFilePath, const ReadableString &targetFilePath)
  14. : sourceFilePath(sourceFilePath), targetFilePath(targetFilePath) {}
  15. };
  16. struct FileOperations {
  17. String projectName;
  18. List<String> newFolderPaths;
  19. List<FileConversion> clonedFiles;
  20. };
  21. // Post-condition: Returns a list of entry names in the path, by simply segmentmenting by folder separators.
  22. static List<String> segmentPath(const ReadableString &path) {
  23. List<String> result;
  24. intptr_t startIndex = 0;
  25. for (intptr_t endIndex = 0; endIndex < string_length(path); endIndex++) {
  26. if (file_isSeparator(path[endIndex])) {
  27. if (startIndex < endIndex) {
  28. result.push(string_exclusiveRange(path, startIndex, endIndex));
  29. }
  30. startIndex = endIndex + 1;
  31. }
  32. }
  33. if (string_length(path) > startIndex) {
  34. result.push(string_exclusiveRange(path, startIndex, string_length(path)));
  35. }
  36. return result;
  37. }
  38. // TODO: Make rewrite it to work in more cases by converting oldOrigin to an absolute path before converting it to the new origin.
  39. // Pre-conditions:
  40. // path is either absolute or relative to oldOrigin.
  41. // Post-condition:
  42. // Returns a path that refers to the same location but relative to newOrigin.
  43. static String changePathOrigin(const ReadableString &path, const ReadableString &oldOrigin, const ReadableString &newOrigin, PathSyntax pathSyntax) {
  44. // Check if the path is absolute.
  45. if (file_hasRoot(path, true)) {
  46. // The path is absolute, so we will not change it into an absolute path, just clean up any redundancy.
  47. return file_optimizePath(path, pathSyntax);
  48. }
  49. String absoluteOldOrigin = file_getAbsolutePath(oldOrigin);
  50. String absoluteNewOrigin = file_getAbsolutePath(newOrigin);
  51. String pathFromCurrent = file_optimizePath(file_combinePaths(absoluteOldOrigin, path, pathSyntax), pathSyntax);
  52. List<String> pathNames = segmentPath(pathFromCurrent);
  53. List<String> newOriginNames = segmentPath(file_optimizePath(absoluteNewOrigin, pathSyntax));
  54. intptr_t reverseOriginDepth = 0;
  55. List<String> forwardOrigin;
  56. bool identicalRoot = true;
  57. for (intptr_t i = 0; i < pathNames.length() || i < newOriginNames.length(); i++) {
  58. if (i < pathNames.length() && i < newOriginNames.length()) {
  59. if (!string_match(pathNames[i], newOriginNames[i])) {
  60. identicalRoot = false;
  61. }
  62. }
  63. if (!identicalRoot) {
  64. if (i < pathNames.length()) {
  65. forwardOrigin.push(pathNames[i]);
  66. }
  67. if (i < newOriginNames.length()) {
  68. reverseOriginDepth++;
  69. }
  70. }
  71. }
  72. List<String> results;
  73. for (intptr_t i = 0; i < reverseOriginDepth; i++) {
  74. results.push(U"..");
  75. }
  76. for (intptr_t i = 0; i < forwardOrigin.length(); i++) {
  77. results.push(forwardOrigin[i]);
  78. }
  79. String result;
  80. for (intptr_t i = 0; i < results.length(); i++) {
  81. if (string_length(result) > 0) {
  82. string_append(result, file_separator(pathSyntax));
  83. }
  84. string_append(result, results[i]);
  85. }
  86. result = file_optimizePath(result, pathSyntax);
  87. return result;
  88. }
  89. static void testRelocation(const ReadableString &path, const ReadableString &oldOrigin, const ReadableString &newOrigin, PathSyntax pathSyntax, const ReadableString &expectedResult) {
  90. String result = changePathOrigin(path, oldOrigin, newOrigin, pathSyntax);
  91. if (!string_match(result, expectedResult)) {
  92. throwError(U"Converting ", path, U" from ", oldOrigin, U" to ", newOrigin, U" expected ", expectedResult, U" as the result but got ", result, U" instead!\n");
  93. }
  94. }
  95. static void regressionTest() {
  96. printText(U"Running regression tests for the cloning project.\n");
  97. testRelocation(U"../someFile.txt", U"folderA/folderC", U"folderB", PathSyntax::Posix, U"../folderA/someFile.txt");
  98. testRelocation(U"someFile.txt", U"folderA", U"folderB", PathSyntax::Windows, U"..\\folderA\\someFile.txt");
  99. testRelocation(U"../../DFPSR/includeFramework.h", U"../../../templates/basic3D", U"./NewProject", PathSyntax::Posix, U"../../../../DFPSR/includeFramework.h");
  100. testRelocation(U"../../DFPSR/includeFramework.h", U"../../../templates/basic3D", U"../NewProject", PathSyntax::Posix, U"../../../DFPSR/includeFramework.h");
  101. testRelocation(U"../../DFPSR/includeFramework.h", U"../../../templates/basic3D", U"../../NewProject", PathSyntax::Posix, U"../../DFPSR/includeFramework.h");
  102. testRelocation(U"../../DFPSR/includeFramework.h", U"../../../templates/basic3D", U"../../../NewProject", PathSyntax::Posix, U"../DFPSR/includeFramework.h");
  103. testRelocation(U"../../DFPSR/includeFramework.h", U"../../../templates/basic3D", U"../../../../NewProject", PathSyntax::Posix, U"../Source/DFPSR/includeFramework.h");
  104. printText(U"Passed all regression tests for the cloning project.\n");
  105. }
  106. // Update paths after #include and #import in c, cpp, h, hpp, m and mm files.
  107. static String updateSourcePaths(const ReadableString &content, const ReadableString &oldParentFolder, const ReadableString &newParentFolder) {
  108. String result;
  109. intptr_t consumed = 0;
  110. int state = 0;
  111. for (intptr_t characterIndex = 0; characterIndex < string_length(content); characterIndex++) {
  112. DsrChar currentCharacter = content[characterIndex];
  113. if (currentCharacter == U'\n') {
  114. state = 0;
  115. } else if (state == 0 && currentCharacter == U'#') {
  116. state = 1;
  117. } else if (state == 1) {
  118. if (string_match(U"include", string_exclusiveRange(content, characterIndex, characterIndex + 7))) {
  119. characterIndex += 6;
  120. state = 2;
  121. } else if (string_match(U"import", string_exclusiveRange(content, characterIndex, characterIndex + 6))) {
  122. characterIndex += 5;
  123. state = 2;
  124. }
  125. } else if (state == 2 && currentCharacter == U'\"') {
  126. // Begin a quoted path.
  127. state = 3;
  128. // Previous text is appended as is.
  129. string_append(result, string_inclusiveRange(content, consumed, characterIndex));
  130. consumed = characterIndex + 1;
  131. } else if (state == 3 && currentCharacter == U'\"') {
  132. // End a quoted path.
  133. state = -1;
  134. String oldPath = string_inclusiveRange(content, consumed, characterIndex - 1);
  135. String newPath = changePathOrigin(oldPath, oldParentFolder, newParentFolder, PathSyntax::Posix);
  136. string_append(result, newPath);
  137. consumed = characterIndex;
  138. if (string_match(newPath, oldPath)) {
  139. printText(U" Nothing needed to change in ", oldPath, U"\n");
  140. } else {
  141. printText(U" Modified path from ", oldPath, U" to ", newPath, U"\n");
  142. }
  143. } else if (state != 3 && !character_isWhiteSpace(currentCharacter)) {
  144. // Abort patterns when getting unexpected characters.
  145. state = -1;
  146. }
  147. }
  148. // Remaining text is appended as is.
  149. string_append(result, string_exclusiveRange(content, consumed, string_length(content)));
  150. return result;
  151. }
  152. // Update paths after Import in DsrProj and DsrHead files.
  153. static String updateProjectPaths(const ReadableString &content, const ReadableString &oldParentFolder, const ReadableString &newParentFolder) {
  154. String result;
  155. intptr_t consumed = 0;
  156. int state = 0;
  157. for (intptr_t characterIndex = 0; characterIndex < string_length(content); characterIndex++) {
  158. DsrChar currentCharacter = content[characterIndex];
  159. if (currentCharacter == U'\n') {
  160. state = 0;
  161. } else if (state == 0) {
  162. if (string_caseInsensitiveMatch(U"Import", string_exclusiveRange(content, characterIndex, characterIndex + 6))) {
  163. characterIndex += 5;
  164. state = 1;
  165. }
  166. } else if (state == 1 && currentCharacter == U'\"') {
  167. // Begin a quoted path.
  168. state = 2;
  169. // Previous text is appended as is.
  170. string_append(result, string_inclusiveRange(content, consumed, characterIndex));
  171. consumed = characterIndex + 1;
  172. } else if (state == 2 && currentCharacter == U'\"') {
  173. // End a quoted path.
  174. state = -1;
  175. String oldPath = string_inclusiveRange(content, consumed, characterIndex - 1);
  176. String newPath = changePathOrigin(oldPath, oldParentFolder, newParentFolder, PathSyntax::Posix);
  177. string_append(result, newPath);
  178. consumed = characterIndex;
  179. if (string_match(newPath, oldPath)) {
  180. printText(U" Nothing needed to change in ", oldPath, U"\n");
  181. } else {
  182. printText(U" Modified path from ", oldPath, U" to ", newPath, U"\n");
  183. }
  184. } else if (state != 2 && !character_isWhiteSpace(currentCharacter)) {
  185. // Abort patterns when getting unexpected characters.
  186. state = -1;
  187. }
  188. }
  189. // Remaining text is appended as is.
  190. string_append(result, string_exclusiveRange(content, consumed, string_length(content)));
  191. return result;
  192. }
  193. static void copyFile(FileOperations &operations, const ReadableString &sourcePath, const ReadableString &targetPath) {
  194. EntryType sourceEntryType = file_getEntryType(sourcePath);
  195. EntryType targetEntryType = file_getEntryType(targetPath);
  196. if (sourceEntryType != EntryType::File) {
  197. throwError(U"The source file ", sourcePath, U" does not exist!\n");
  198. }
  199. if (targetEntryType != EntryType::NotFound) {
  200. throwError(U"The target file ", targetPath, U" already exists!\n");
  201. } else {
  202. Buffer fileContent = file_loadBuffer(sourcePath);
  203. if (!buffer_exists(fileContent)) {
  204. throwError(U"The source file ", sourcePath, U" could not be loaded!\n");
  205. }
  206. ReadableString pathless = file_getPathlessName(sourcePath);
  207. ReadableString extension = file_getExtension(pathless);
  208. if (string_caseInsensitiveMatch(extension, U"DsrProj")
  209. || string_caseInsensitiveMatch(extension, U"DsrHead")) {
  210. //patterns.pushConstruct(U"Import \"", U"", U"\"");
  211. fileContent = string_saveToMemory(updateProjectPaths(string_loadFromMemory(fileContent), file_getRelativeParentFolder(sourcePath), file_getRelativeParentFolder(targetPath)), CharacterEncoding::Raw_Latin1);
  212. } else if (string_caseInsensitiveMatch(extension, U"sh")
  213. || string_caseInsensitiveMatch(extension, U"bat")) {
  214. String sourceParent = file_getRelativeParentFolder(sourcePath);
  215. String targetParent = file_getRelativeParentFolder(targetPath);
  216. // Entirely replace the old scripts for calling the build system with new ones, because pattern matching without clearly defined bounds is too error-prone.
  217. if (string_caseInsensitiveMatch(pathless, U"build_windows.bat")) {
  218. String buildScriptPath = changePathOrigin(U"..\\..\\tools\\builder\\buildProject.bat", sourceParent, targetParent, PathSyntax::Windows);
  219. String content = string_combine(buildScriptPath, U" ", operations.projectName, U".DsrProj Windows %@%\n");
  220. fileContent = string_saveToMemory(content, CharacterEncoding::Raw_Latin1);
  221. } else if (string_caseInsensitiveMatch(pathless, U"build_linux.sh")) {
  222. String buildScriptPath = changePathOrigin(U"../../tools/builder/buildProject.sh", sourceParent, targetParent, PathSyntax::Posix);
  223. String content = string_combine(
  224. U"chmod +x ", buildScriptPath, U"\n",
  225. buildScriptPath ,U" ", operations.projectName, U".DsrProj Linux $@\n"
  226. );
  227. fileContent = string_saveToMemory(content, CharacterEncoding::Raw_Latin1);
  228. } else if (string_caseInsensitiveMatch(pathless, U"build_macos.sh")) {
  229. String buildScriptPath = changePathOrigin(U"../../tools/builder/buildProject.sh", sourceParent, targetParent, PathSyntax::Posix);
  230. String content = string_combine(
  231. U"chmod +x ", buildScriptPath, U"\n",
  232. buildScriptPath ,U" ", operations.projectName, U".DsrProj MacOS $@\n"
  233. );
  234. fileContent = string_saveToMemory(content, CharacterEncoding::Raw_Latin1);
  235. }
  236. } else if (string_caseInsensitiveMatch(extension, U"sh")) {
  237. //TODO: Look for paths containing U"/builder/buildProject.sh", segment the whole path, and update path origin.
  238. //fileContent = string_saveToMemory(updateShellPaths(string_loadFromMemory(fileContent), file_getRelativeParentFolder(sourcePath), file_getRelativeParentFolder(targetPath)), CharacterEncoding::Raw_Latin1);
  239. } else if (string_caseInsensitiveMatch(extension, U"c")
  240. || string_caseInsensitiveMatch(extension, U"cpp")
  241. || string_caseInsensitiveMatch(extension, U"h")
  242. || string_caseInsensitiveMatch(extension, U"hpp")
  243. || string_caseInsensitiveMatch(extension, U"m")
  244. || string_caseInsensitiveMatch(extension, U"mm")) {
  245. fileContent = string_saveToMemory(updateSourcePaths(string_loadFromMemory(fileContent), file_getRelativeParentFolder(sourcePath), file_getRelativeParentFolder(targetPath)), CharacterEncoding::BOM_UTF8);
  246. }
  247. if (!file_saveBuffer(targetPath, fileContent)) {
  248. throwError(U"The target file ", targetPath, U" could not be saved!\n");
  249. }
  250. }
  251. }
  252. static bool createFolder_deferred(FileOperations &operations, const ReadableString &folderPath) {
  253. EntryType targetEntryType = file_getEntryType(folderPath);
  254. if (targetEntryType == EntryType::Folder) {
  255. return true;
  256. } else if (targetEntryType == EntryType::File) {
  257. printText(U"The folder to create ", folderPath, U" is an pre-existing file and can not be overwritten with a folder!\n");
  258. return false;
  259. } else if (targetEntryType == EntryType::NotFound) {
  260. String parentFolder = file_getRelativeParentFolder(folderPath);
  261. if (string_length(parentFolder) < string_length(folderPath) && createFolder_deferred(operations, parentFolder)) {
  262. operations.newFolderPaths.push(folderPath);
  263. return true;
  264. } else {
  265. printText(U"Failed to create a parent folder at ", parentFolder, U"!\n");
  266. return false;
  267. }
  268. } else {
  269. printText(U"The folder to create ", folderPath, U" can not be overwritten!\n");
  270. return false;
  271. }
  272. }
  273. static void copyFolder_deferred(FileOperations &operations, const ReadableString &sourcePath, const ReadableString &targetPath) {
  274. if (!createFolder_deferred(operations, targetPath)) {
  275. throwError(U"Failed to create a folder at ", targetPath, U"!\n");
  276. } else {
  277. if (!file_getFolderContent(sourcePath, [&operations, targetPath](const ReadableString& entryPath, const ReadableString& entryName, EntryType entryType) {
  278. if (entryType == EntryType::File) {
  279. operations.clonedFiles.pushConstruct(entryPath, file_combinePaths(targetPath, entryName));
  280. } else if (entryType == EntryType::Folder) {
  281. copyFolder_deferred(operations, entryPath, file_combinePaths(targetPath, entryName));
  282. }
  283. })) {
  284. printText("Failed to explore ", sourcePath, "\n");
  285. }
  286. }
  287. }
  288. enum class ExpectedArgument {
  289. Flag, Source, Target, Name
  290. };
  291. DSR_MAIN_CALLER(dsrMain)
  292. void dsrMain(List<String> args) {
  293. if (args.length() <= 1) {
  294. regressionTest();
  295. return;
  296. }
  297. // Example calls:
  298. // ./Clone -s ../../../templates/basic3D -t ./NewProject -n NewProject
  299. // ./Clone --source ../../../templates/basic3D --target ./NewProject --name NewProject
  300. String source;
  301. String target;
  302. String projectName;
  303. ExpectedArgument expectedArgument = ExpectedArgument::Flag;
  304. for (int i = 1; i < args.length(); i++) {
  305. ReadableString argument = args[i];
  306. if (expectedArgument == ExpectedArgument::Flag) {
  307. if (string_caseInsensitiveMatch(argument, U"-s") || string_caseInsensitiveMatch(argument, U"--source")) {
  308. expectedArgument = ExpectedArgument::Source;
  309. } else if (string_caseInsensitiveMatch(argument, U"-t") || string_caseInsensitiveMatch(argument, U"--target")) {
  310. expectedArgument = ExpectedArgument::Target;
  311. } else if (string_caseInsensitiveMatch(argument, U"-n") || string_caseInsensitiveMatch(argument, U"--name")) {
  312. expectedArgument = ExpectedArgument::Name;
  313. } else {
  314. sendWarning(U"Unrecognized flag ", argument, U" given to project cloning!\n");
  315. }
  316. } else if (expectedArgument == ExpectedArgument::Source) {
  317. EntryType sourceEntryType = file_getEntryType(argument);
  318. if (sourceEntryType == EntryType::Folder) {
  319. printText(U"Using ", argument, U" as the source folder path.\n");
  320. source = argument;
  321. } else if (sourceEntryType == EntryType::File) {
  322. throwError(U"The source ", argument, U" is a file and can not be used as a source folder for project cloning!\n");
  323. } else if (sourceEntryType == EntryType::NotFound) {
  324. throwError(U"The source ", argument, U" can not be found! The source path must refer to an existing folder to clone from.\n");
  325. }
  326. expectedArgument = ExpectedArgument::Flag;
  327. } else if (expectedArgument == ExpectedArgument::Target) {
  328. EntryType targetEntryType = file_getEntryType(argument);
  329. if (targetEntryType == EntryType::Folder) {
  330. printText(U"Using ", argument, U" as the target folder path.\n");
  331. target = argument;
  332. } else if (targetEntryType == EntryType::File) {
  333. throwError(U"The target ", argument, U" is a file and can not be used as a target folder for project cloning!\n");
  334. } else if (targetEntryType == EntryType::NotFound) {
  335. printText(U"Using ", argument, U" as the target folder path.\n");
  336. target = argument;
  337. }
  338. expectedArgument = ExpectedArgument::Flag;
  339. } else if (expectedArgument == ExpectedArgument::Name) {
  340. projectName = argument;
  341. expectedArgument = ExpectedArgument::Flag;
  342. }
  343. }
  344. if (string_length(source) == 0 && string_length(target) == 0) {
  345. throwError(U"Cloning project needs both source and target folder paths!\n");
  346. } else if (string_length(source) == 0) {
  347. throwError(U"Missing source folder to clone from!\n");
  348. } else if (string_length(target) == 0) {
  349. throwError(U"Missing target folder to clone to!\n");
  350. }
  351. printText(U"Cloning project from ", source, U" to ", target, U"\n");
  352. // List operations to perform ahead of time to prevent bottomless recursion when cloning into a subfolder of the source folder.
  353. FileOperations operations;
  354. copyFolder_deferred(operations, source, target);
  355. // Rename things.
  356. for (intptr_t fileIndex = 0; fileIndex < operations.clonedFiles.length(); fileIndex++) {
  357. ReadableString fileName = file_getPathlessName(operations.clonedFiles[fileIndex].sourceFilePath);
  358. // Assuming that there is only one project in the folder.
  359. if (string_caseInsensitiveMatch(file_getExtension(fileName), U"DsrProj")) {
  360. // Check if a project name was selected.
  361. if (string_length(projectName) == 0) {
  362. // No project name selected, so use the file's existing name as the project name.
  363. operations.projectName = file_getExtensionless(fileName);
  364. } else {
  365. // A project name was selected, so rename the project file.
  366. ReadableString parentFolder = file_getAbsoluteParentFolder(operations.clonedFiles[fileIndex].targetFilePath);
  367. operations.clonedFiles[fileIndex].targetFilePath = file_combinePaths(parentFolder, string_combine(projectName, U".DsrProj"));
  368. operations.projectName = projectName;
  369. }
  370. }
  371. }
  372. // Create folders.
  373. for (intptr_t folderIndex = 0; folderIndex < operations.newFolderPaths.length(); folderIndex++) {
  374. ReadableString newFolderPath = operations.newFolderPaths[folderIndex];
  375. printText(U"Creating a new folder at ", newFolderPath, U"\n");
  376. file_createFolder(newFolderPath);
  377. }
  378. // Clone files.
  379. for (intptr_t fileIndex = 0; fileIndex < operations.clonedFiles.length(); fileIndex++) {
  380. FileConversion conversion = operations.clonedFiles[fileIndex];
  381. printText(U"Cloning file from ", conversion.sourceFilePath, U" to ", conversion.targetFilePath, U"\n");
  382. copyFile(operations, conversion.sourceFilePath, conversion.targetFilePath);
  383. }
  384. }