Project.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 = create_file(model().full_path(index));
  38. callback(*file);
  39. });
  40. }
  41. NonnullRefPtr<ProjectFile> Project::create_file(const String& path) const
  42. {
  43. auto full_path = to_absolute_path(path);
  44. return ProjectFile::construct_with_name(full_path);
  45. }
  46. String Project::to_absolute_path(String const& path) const
  47. {
  48. if (LexicalPath { path }.is_absolute()) {
  49. return path;
  50. }
  51. return LexicalPath { String::formatted("{}/{}", m_root_path, path) }.string();
  52. }
  53. }