main.cpp 19 KB

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