Project.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 <LibCore/File.h>
  9. namespace HackStudio {
  10. Project::Project(const String& 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(const String& root_path)
  16. {
  17. if (!Core::File::is_directory(root_path))
  18. return {};
  19. return adopt_own(*new Project(root_path));
  20. }
  21. template<typename Callback>
  22. static void traverse_model(const GUI::FileSystemModel& model, const GUI::ModelIndex& index, Callback callback)
  23. {
  24. if (index.is_valid())
  25. callback(index);
  26. auto row_count = model.row_count(index);
  27. if (!row_count)
  28. return;
  29. for (int row = 0; row < row_count; ++row) {
  30. auto child_index = model.index(row, GUI::FileSystemModel::Column::Name, index);
  31. traverse_model(model, child_index, callback);
  32. }
  33. }
  34. void Project::for_each_text_file(Function<void(const ProjectFile&)> callback) const
  35. {
  36. traverse_model(model(), {}, [&](auto& index) {
  37. auto file = get_file(model().full_path(index));
  38. if (file)
  39. callback(*file);
  40. });
  41. }
  42. NonnullRefPtr<ProjectFile> Project::get_file(const String& path) const
  43. {
  44. auto full_path = to_absolute_path(path);
  45. for (auto& file : m_files) {
  46. if (file.name() == full_path)
  47. return file;
  48. }
  49. auto file = ProjectFile::construct_with_name(full_path);
  50. m_files.append(file);
  51. return file;
  52. }
  53. String Project::to_absolute_path(const String& path) const
  54. {
  55. if (LexicalPath { path }.is_absolute()) {
  56. return path;
  57. }
  58. return LexicalPath { String::formatted("{}/{}", m_root_path, path) }.string();
  59. }
  60. }