ProjectBuilder.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. * Copyright (c) 2022, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "ProjectBuilder.h"
  7. #include <AK/LexicalPath.h>
  8. #include <LibCore/Command.h>
  9. #include <LibCore/File.h>
  10. #include <LibRegex/Regex.h>
  11. #include <fcntl.h>
  12. #include <sys/stat.h>
  13. namespace HackStudio {
  14. ProjectBuilder::ProjectBuilder(NonnullRefPtr<TerminalWrapper> terminal, Project const& project)
  15. : m_project_root(project.root_path())
  16. , m_project(project)
  17. , m_terminal(move(terminal))
  18. , m_is_serenity(project.project_is_serenity() ? IsSerenityRepo::Yes : IsSerenityRepo::No)
  19. {
  20. }
  21. ErrorOr<void> ProjectBuilder::build(StringView active_file)
  22. {
  23. m_terminal->clear_including_history();
  24. if (auto command = m_project.config()->build_command(); command.has_value()) {
  25. TRY(m_terminal->run_command(command.value()));
  26. return {};
  27. }
  28. if (active_file.is_null())
  29. return Error::from_string_literal("no active file");
  30. if (active_file.ends_with(".js"sv)) {
  31. TRY(m_terminal->run_command(String::formatted("js -A {}", active_file)));
  32. return {};
  33. }
  34. if (m_is_serenity == IsSerenityRepo::No) {
  35. TRY(verify_make_is_installed());
  36. TRY(m_terminal->run_command("make"));
  37. return {};
  38. }
  39. TRY(update_active_file(active_file));
  40. return build_serenity_component();
  41. }
  42. ErrorOr<void> ProjectBuilder::run(StringView active_file)
  43. {
  44. if (auto command = m_project.config()->run_command(); command.has_value()) {
  45. TRY(m_terminal->run_command(command.value()));
  46. return {};
  47. }
  48. if (active_file.is_null())
  49. return Error::from_string_literal("no active file");
  50. if (active_file.ends_with(".js"sv)) {
  51. TRY(m_terminal->run_command(String::formatted("js {}", active_file)));
  52. return {};
  53. }
  54. if (m_is_serenity == IsSerenityRepo::No) {
  55. TRY(verify_make_is_installed());
  56. TRY(m_terminal->run_command("make run"));
  57. return {};
  58. }
  59. TRY(update_active_file(active_file));
  60. return run_serenity_component();
  61. }
  62. ErrorOr<void> ProjectBuilder::run_serenity_component()
  63. {
  64. auto relative_path_to_dir = LexicalPath::relative_path(LexicalPath::dirname(m_serenity_component_cmake_file), m_project_root);
  65. TRY(m_terminal->run_command(LexicalPath::join(relative_path_to_dir, m_serenity_component_name).string(), build_directory()));
  66. return {};
  67. }
  68. ErrorOr<void> ProjectBuilder::update_active_file(StringView active_file)
  69. {
  70. TRY(verify_cmake_is_installed());
  71. auto cmake_file = find_cmake_file_for(active_file);
  72. if (!cmake_file.has_value()) {
  73. warnln("did not find cmake file for: {}", active_file);
  74. return Error::from_string_literal("did not find cmake file");
  75. }
  76. if (m_serenity_component_cmake_file == cmake_file.value())
  77. return {};
  78. m_serenity_component_cmake_file = cmake_file.value();
  79. m_serenity_component_name = TRY(component_name(m_serenity_component_cmake_file));
  80. TRY(initialize_build_directory());
  81. return {};
  82. }
  83. ErrorOr<void> ProjectBuilder::build_serenity_component()
  84. {
  85. TRY(verify_make_is_installed());
  86. TRY(m_terminal->run_command(String::formatted("make {}", m_serenity_component_name), build_directory(), TerminalWrapper::WaitForExit::Yes, "Make failed"sv));
  87. return {};
  88. }
  89. ErrorOr<String> ProjectBuilder::component_name(StringView cmake_file_path)
  90. {
  91. auto content = TRY(Core::File::open(cmake_file_path, Core::OpenMode::ReadOnly))->read_all();
  92. static Regex<ECMA262> const component_name(R"~~~(serenity_component\([\s]*(\w+)[\s\S]*\))~~~");
  93. RegexResult result;
  94. if (!component_name.search(StringView { content }, result))
  95. return Error::from_string_literal("component not found");
  96. return String { result.capture_group_matches.at(0).at(0).view.string_view() };
  97. }
  98. ErrorOr<void> ProjectBuilder::initialize_build_directory()
  99. {
  100. if (!Core::File::exists(build_directory())) {
  101. if (mkdir(LexicalPath::join(build_directory()).string().characters(), 0700)) {
  102. return Error::from_errno(errno);
  103. }
  104. }
  105. auto cmake_file_path = LexicalPath::join(build_directory(), "CMakeLists.txt"sv).string();
  106. if (Core::File::exists(cmake_file_path))
  107. MUST(Core::File::remove(cmake_file_path, Core::File::RecursionMode::Disallowed, false));
  108. auto cmake_file = TRY(Core::File::open(cmake_file_path, Core::OpenMode::WriteOnly));
  109. cmake_file->write(generate_cmake_file_content());
  110. TRY(m_terminal->run_command(String::formatted("cmake -S {} -DHACKSTUDIO_BUILD=ON -DHACKSTUDIO_BUILD_CMAKE_FILE={}"
  111. " -DENABLE_UNICODE_DATABASE_DOWNLOAD=OFF",
  112. m_project_root, cmake_file_path),
  113. build_directory(), TerminalWrapper::WaitForExit::Yes, "CMake error"sv));
  114. return {};
  115. }
  116. Optional<String> ProjectBuilder::find_cmake_file_for(StringView file_path) const
  117. {
  118. auto directory = LexicalPath::dirname(file_path);
  119. while (!directory.is_empty()) {
  120. auto cmake_path = LexicalPath::join(m_project_root, directory, "CMakeLists.txt"sv);
  121. if (Core::File::exists(cmake_path.string()))
  122. return cmake_path.string();
  123. directory = LexicalPath::dirname(directory);
  124. }
  125. return {};
  126. }
  127. String ProjectBuilder::generate_cmake_file_content() const
  128. {
  129. StringBuilder builder;
  130. builder.appendff("add_subdirectory({})\n", LexicalPath::dirname(m_serenity_component_cmake_file));
  131. auto defined_libraries = get_defined_libraries();
  132. for (auto& library : defined_libraries) {
  133. builder.appendff("add_library({} SHARED IMPORTED GLOBAL)\n", library.key);
  134. builder.appendff("set_target_properties({} PROPERTIES IMPORTED_LOCATION {})\n", library.key, library.value->path);
  135. if (library.key == "LibCStaticWithoutDeps"sv || library.key == "DumpLayoutTree"sv)
  136. continue;
  137. // We need to specify the dependencies for each defined library in CMake because some applications do not specify
  138. // all of their direct dependencies in the CMakeLists file.
  139. // For example, a target may directly use LibGFX but only specify LibGUI as a dependency (which in turn depends on LibGFX).
  140. // In this example, if we don't specify the dependencies of LibGUI in the CMake file, linking will fail because of undefined LibGFX symbols.
  141. builder.appendff("target_link_libraries({} INTERFACE {})\n", library.key, String::join(' ', library.value->dependencies));
  142. }
  143. return builder.to_string();
  144. }
  145. HashMap<String, NonnullOwnPtr<ProjectBuilder::LibraryInfo>> ProjectBuilder::get_defined_libraries()
  146. {
  147. HashMap<String, NonnullOwnPtr<ProjectBuilder::LibraryInfo>> libraries;
  148. for_each_library_definition([&libraries](String name, String path) {
  149. libraries.set(name, make<ProjectBuilder::LibraryInfo>(move(path)));
  150. });
  151. for_each_library_dependencies([&libraries](String name, Vector<StringView> const& dependencies) {
  152. auto library = libraries.get(name);
  153. if (!library.has_value())
  154. return;
  155. for (auto const& dependency : dependencies) {
  156. if (libraries.contains(dependency))
  157. library.value()->dependencies.append(dependency);
  158. }
  159. });
  160. return libraries;
  161. }
  162. void ProjectBuilder::for_each_library_definition(Function<void(String, String)> func)
  163. {
  164. Vector<String> arguments = { "-c", "find Userland -name CMakeLists.txt | xargs grep serenity_lib" };
  165. auto res = Core::command("/bin/sh", arguments, {});
  166. if (res.is_error()) {
  167. warnln("{}", res.error());
  168. return;
  169. }
  170. static Regex<ECMA262> const parse_library_definition(R"~~~(.+:serenity_lib[c]?\((\w+) (\w+)\).*)~~~");
  171. for (auto& line : res.value().output.split('\n')) {
  172. RegexResult result;
  173. if (!parse_library_definition.search(line, result))
  174. continue;
  175. if (result.capture_group_matches.size() != 1 || result.capture_group_matches[0].size() != 2)
  176. continue;
  177. auto library_name = result.capture_group_matches.at(0).at(0).view.string_view();
  178. auto library_obj_name = result.capture_group_matches.at(0).at(1).view.string_view();
  179. auto so_path = String::formatted("{}.so", LexicalPath::join("/usr/lib"sv, String::formatted("lib{}", library_obj_name)).string());
  180. func(library_name, so_path);
  181. }
  182. // ssp is defined with "add_library" so it doesn't get picked up with the current logic for finding library definitions.
  183. func("ssp", "/usr/lib/libssp.a");
  184. }
  185. void ProjectBuilder::for_each_library_dependencies(Function<void(String, Vector<StringView>)> func)
  186. {
  187. Vector<String> arguments = { "-c", "find Userland/Libraries -name CMakeLists.txt | xargs grep target_link_libraries" };
  188. auto res = Core::command("/bin/sh", arguments, {});
  189. if (res.is_error()) {
  190. warnln("{}", res.error());
  191. return;
  192. }
  193. static Regex<ECMA262> const parse_library_definition(R"~~~(.+:target_link_libraries\((\w+) ([\w\s]+)\).*)~~~");
  194. for (auto& line : res.value().output.split('\n')) {
  195. RegexResult result;
  196. if (!parse_library_definition.search(line, result))
  197. continue;
  198. if (result.capture_group_matches.size() != 1 || result.capture_group_matches[0].size() != 2)
  199. continue;
  200. auto library_name = result.capture_group_matches.at(0).at(0).view.string_view();
  201. auto dependencies_string = result.capture_group_matches.at(0).at(1).view.string_view();
  202. func(library_name, dependencies_string.split_view(' '));
  203. }
  204. }
  205. ErrorOr<void> ProjectBuilder::verify_cmake_is_installed()
  206. {
  207. auto res = Core::command("cmake --version", {});
  208. if (!res.is_error() && res.value().exit_code == 0)
  209. return {};
  210. return Error::from_string_literal("CMake port is not installed");
  211. }
  212. ErrorOr<void> ProjectBuilder::verify_make_is_installed()
  213. {
  214. auto res = Core::command("make --version", {});
  215. if (!res.is_error() && res.value().exit_code == 0)
  216. return {};
  217. return Error::from_string_literal("Make port is not installed");
  218. }
  219. String ProjectBuilder::build_directory() const
  220. {
  221. return LexicalPath::join(m_project_root, "Build"sv).string();
  222. }
  223. }