Project.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Project.h"
  7. #include "HackStudio.h"
  8. #include <LibFileSystem/FileSystem.h>
  9. namespace HackStudio {
  10. Project::Project(ByteString const& root_path)
  11. : m_root_path(root_path)
  12. {
  13. m_model = GUI::FileSystemModel::create(root_path, GUI::FileSystemModel::Mode::FilesAndDirectories);
  14. }
  15. OwnPtr<Project> Project::open_with_root_path(ByteString const& root_path)
  16. {
  17. VERIFY(LexicalPath(root_path).is_absolute());
  18. if (!FileSystem::is_directory(root_path))
  19. return {};
  20. return adopt_own(*new Project(root_path));
  21. }
  22. template<typename Callback>
  23. static void traverse_model(const GUI::FileSystemModel& model, const GUI::ModelIndex& index, Callback callback)
  24. {
  25. if (index.is_valid())
  26. callback(index);
  27. auto row_count = model.row_count(index);
  28. if (!row_count)
  29. return;
  30. for (int row = 0; row < row_count; ++row) {
  31. auto child_index = model.index(row, GUI::FileSystemModel::Column::Name, index);
  32. traverse_model(model, child_index, callback);
  33. }
  34. }
  35. void Project::for_each_text_file(Function<void(ProjectFile const&)> callback) const
  36. {
  37. traverse_model(model(), {}, [&](auto& index) {
  38. auto file = create_file(model().full_path(index));
  39. callback(*file);
  40. });
  41. }
  42. NonnullRefPtr<ProjectFile> Project::create_file(ByteString const& path) const
  43. {
  44. auto full_path = to_absolute_path(path);
  45. return ProjectFile::construct_with_name(full_path);
  46. }
  47. ByteString Project::to_absolute_path(ByteString const& path) const
  48. {
  49. if (LexicalPath { path }.is_absolute()) {
  50. return path;
  51. }
  52. return LexicalPath { ByteString::formatted("{}/{}", m_root_path, path) }.string();
  53. }
  54. bool Project::project_is_serenity() const
  55. {
  56. // FIXME: Improve this heuristic
  57. // Running "Meta/serenity.sh copy-src" installs the serenity repository at this path in the home directory
  58. return m_root_path.ends_with("Source/serenity"sv);
  59. }
  60. NonnullOwnPtr<ProjectConfig> Project::config() const
  61. {
  62. auto config_or_error = ProjectConfig::try_load_project_config(LexicalPath::absolute_path(m_root_path, config_file_path));
  63. if (config_or_error.is_error())
  64. return ProjectConfig::create_empty();
  65. return config_or_error.release_value();
  66. }
  67. }