ProjectTemplate.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /*
  2. * Copyright (c) 2021, Nick Vella <nick@nxk.io>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "ProjectTemplate.h"
  7. #include <AK/LexicalPath.h>
  8. #include <AK/String.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/ConfigFile.h>
  12. #include <LibCore/DirIterator.h>
  13. #include <LibCore/File.h>
  14. #include <assert.h>
  15. #include <fcntl.h>
  16. #include <spawn.h>
  17. #include <sys/stat.h>
  18. #include <sys/wait.h>
  19. #include <unistd.h>
  20. // FIXME: shameless copy+paste from Userland/cp. We should have system-wide file management functions.
  21. // Issue #5209
  22. bool copy_file_or_directory(String, String, bool, bool);
  23. bool copy_file(String, String, const struct stat&, int);
  24. bool copy_directory(String, String, bool);
  25. namespace HackStudio {
  26. ProjectTemplate::ProjectTemplate(const String& id, const String& name, const String& description, const GUI::Icon& icon, int priority)
  27. : m_id(id)
  28. , m_name(name)
  29. , m_description(description)
  30. , m_icon(icon)
  31. , m_priority(priority)
  32. {
  33. }
  34. RefPtr<ProjectTemplate> ProjectTemplate::load_from_manifest(const String& manifest_path)
  35. {
  36. auto config = Core::ConfigFile::open(manifest_path);
  37. if (!config->has_group("HackStudioTemplate")
  38. || !config->has_key("HackStudioTemplate", "Name")
  39. || !config->has_key("HackStudioTemplate", "Description")
  40. || !config->has_key("HackStudioTemplate", "IconName32x"))
  41. return {};
  42. auto id = LexicalPath(manifest_path).title();
  43. auto name = config->read_entry("HackStudioTemplate", "Name");
  44. auto description = config->read_entry("HackStudioTemplate", "Description");
  45. int priority = config->read_num_entry("HackStudioTemplate", "Priority", 0);
  46. // Attempt to read in the template icons
  47. // Fallback to a generic executable icon if one isn't found
  48. auto icon = GUI::Icon::default_icon("filetype-executable");
  49. auto bitmap_path_32 = String::formatted("/res/icons/hackstudio/templates-32x32/{}.png", config->read_entry("HackStudioTemplate", "IconName32x"));
  50. if (Core::File::exists(bitmap_path_32)) {
  51. auto bitmap32 = Gfx::Bitmap::load_from_file(bitmap_path_32);
  52. icon = GUI::Icon(move(bitmap32));
  53. }
  54. return adopt_ref(*new ProjectTemplate(id, name, description, icon, priority));
  55. }
  56. Result<void, String> ProjectTemplate::create_project(const String& name, const String& path)
  57. {
  58. // Check if a file or directory already exists at the project path
  59. if (Core::File::exists(path))
  60. return String("File or directory already exists at specified location.");
  61. dbgln("Creating project at path '{}' with name '{}'", path, name);
  62. // Verify that the template content directory exists. If it does, copy it's contents.
  63. // Otherwise, create an empty directory at the project path.
  64. if (Core::File::is_directory(content_path())) {
  65. if (!copy_directory(content_path(), path, false))
  66. return String("Failed to copy template contents.");
  67. } else {
  68. dbgln("No template content directory found for '{}', creating an empty directory for the project.", m_id);
  69. int rc;
  70. if ((rc = mkdir(path.characters(), 0755)) < 0) {
  71. return String::formatted("Failed to mkdir empty project directory, error: {}, rc: {}.", strerror(errno), rc);
  72. }
  73. }
  74. // Check for an executable post-create script in $TEMPLATES_DIR/$ID.postcreate,
  75. // and run it with the path and name
  76. auto postcreate_script_path = LexicalPath::canonicalized_path(String::formatted("{}/{}.postcreate", templates_path(), m_id));
  77. struct stat postcreate_st;
  78. int result = stat(postcreate_script_path.characters(), &postcreate_st);
  79. if (result == 0 && (postcreate_st.st_mode & S_IXOTH) == S_IXOTH) {
  80. dbgln("Running post-create script '{}'", postcreate_script_path);
  81. // Generate a namespace-safe project name (replace hyphens with underscores)
  82. String namespace_safe(name.characters());
  83. namespace_safe.replace("-", "_", true);
  84. pid_t child_pid;
  85. const char* argv[] = { postcreate_script_path.characters(), name.characters(), path.characters(), namespace_safe.characters(), nullptr };
  86. if ((errno = posix_spawn(&child_pid, postcreate_script_path.characters(), nullptr, nullptr, const_cast<char**>(argv), environ))) {
  87. perror("posix_spawn");
  88. return String("Failed to spawn project post-create script.");
  89. }
  90. // Command spawned, wait for exit.
  91. int status;
  92. if (waitpid(child_pid, &status, 0) < 0)
  93. return String("Failed to spawn project post-create script.");
  94. int child_error = WEXITSTATUS(status);
  95. dbgln("Post-create script exited with code {}", child_error);
  96. if (child_error != 0)
  97. return String("Project post-creation script exited with non-zero error code.");
  98. }
  99. return {};
  100. }
  101. }
  102. // FIXME: shameless copy+paste from Userland/cp. We should have system-wide file management functions.
  103. // Issue #5209
  104. bool copy_file_or_directory(String src_path, String dst_path, bool recursion_allowed, bool link)
  105. {
  106. int src_fd = open(src_path.characters(), O_RDONLY);
  107. if (src_fd < 0) {
  108. perror("open src");
  109. return false;
  110. }
  111. struct stat src_stat;
  112. int rc = fstat(src_fd, &src_stat);
  113. if (rc < 0) {
  114. perror("stat src");
  115. return false;
  116. }
  117. if (S_ISDIR(src_stat.st_mode)) {
  118. if (!recursion_allowed) {
  119. fprintf(stderr, "cp: -R not specified; omitting directory '%s'\n", src_path.characters());
  120. return false;
  121. }
  122. return copy_directory(src_path, dst_path, link);
  123. }
  124. if (link) {
  125. if (::link(src_path.characters(), dst_path.characters()) < 0) {
  126. perror("link");
  127. return false;
  128. }
  129. return true;
  130. }
  131. return copy_file(src_path, dst_path, src_stat, src_fd);
  132. }
  133. bool copy_file(String src_path, String dst_path, const struct stat& src_stat, int src_fd)
  134. {
  135. // Get umask
  136. auto my_umask = umask(0);
  137. umask(my_umask);
  138. // NOTE: We don't copy the set-uid and set-gid bits.
  139. mode_t mode = (src_stat.st_mode & ~my_umask) & ~06000;
  140. int dst_fd = creat(dst_path.characters(), mode);
  141. if (dst_fd < 0) {
  142. if (errno != EISDIR) {
  143. perror("open dst");
  144. return false;
  145. }
  146. StringBuilder builder;
  147. builder.append(dst_path);
  148. builder.append('/');
  149. builder.append(LexicalPath(src_path).basename());
  150. dst_path = builder.to_string();
  151. dst_fd = creat(dst_path.characters(), 0666);
  152. if (dst_fd < 0) {
  153. perror("open dst");
  154. return false;
  155. }
  156. }
  157. if (src_stat.st_size > 0) {
  158. if (ftruncate(dst_fd, src_stat.st_size) < 0) {
  159. perror("cp: ftruncate");
  160. return false;
  161. }
  162. }
  163. for (;;) {
  164. char buffer[32768];
  165. ssize_t nread = read(src_fd, buffer, sizeof(buffer));
  166. if (nread < 0) {
  167. perror("read src");
  168. return false;
  169. }
  170. if (nread == 0)
  171. break;
  172. ssize_t remaining_to_write = nread;
  173. char* bufptr = buffer;
  174. while (remaining_to_write) {
  175. ssize_t nwritten = write(dst_fd, bufptr, remaining_to_write);
  176. if (nwritten < 0) {
  177. perror("write dst");
  178. return false;
  179. }
  180. assert(nwritten > 0);
  181. remaining_to_write -= nwritten;
  182. bufptr += nwritten;
  183. }
  184. }
  185. close(src_fd);
  186. close(dst_fd);
  187. return true;
  188. }
  189. bool copy_directory(String src_path, String dst_path, bool link)
  190. {
  191. int rc = mkdir(dst_path.characters(), 0755);
  192. if (rc < 0) {
  193. perror("cp: mkdir");
  194. return false;
  195. }
  196. String src_rp = Core::File::real_path_for(src_path);
  197. src_rp = String::formatted("{}/", src_rp);
  198. String dst_rp = Core::File::real_path_for(dst_path);
  199. dst_rp = String::formatted("{}/", dst_rp);
  200. if (!dst_rp.is_empty() && dst_rp.starts_with(src_rp)) {
  201. fprintf(stderr, "cp: Cannot copy %s into itself (%s)\n",
  202. src_path.characters(), dst_path.characters());
  203. return false;
  204. }
  205. Core::DirIterator di(src_path, Core::DirIterator::SkipDots);
  206. if (di.has_error()) {
  207. fprintf(stderr, "cp: DirIterator: %s\n", di.error_string());
  208. return false;
  209. }
  210. while (di.has_next()) {
  211. String filename = di.next_path();
  212. bool is_copied = copy_file_or_directory(
  213. String::formatted("{}/{}", src_path, filename),
  214. String::formatted("{}/{}", dst_path, filename),
  215. true, link);
  216. if (!is_copied) {
  217. return false;
  218. }
  219. }
  220. return true;
  221. }