files.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from pathlib import Path
  2. from typing import Any
  3. class WorkspaceFile:
  4. name: str
  5. children: list['WorkspaceFile']
  6. def __init__(self, name: str, children: list['WorkspaceFile']):
  7. self.name = name
  8. self.children = children
  9. def to_dict(self) -> dict[str, Any]:
  10. """Converts the File object to a dictionary.
  11. Returns:
  12. The dictionary representation of the File object.
  13. """
  14. return {
  15. 'name': self.name,
  16. 'children': [child.to_dict() for child in self.children],
  17. }
  18. def get_folder_structure(workdir: Path) -> WorkspaceFile:
  19. """Gets the folder structure of a directory.
  20. Args:
  21. workdir: The directory path.
  22. Returns:
  23. The folder structure.
  24. """
  25. root = WorkspaceFile(name=workdir.name, children=[])
  26. for item in workdir.iterdir():
  27. if item.is_dir():
  28. dir = get_folder_structure(item)
  29. if dir.children:
  30. root.children.append(dir)
  31. else:
  32. root.children.append(WorkspaceFile(name=item.name, children=[]))
  33. return root