file_utils.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (c) Microsoft Corporation. All rights reserved.
  2. # Licensed under the MIT License.
  3. from __future__ import annotations
  4. import os
  5. import pathlib
  6. import typing
  7. def path_match_suffix_ignore_case(path: pathlib.Path | str, suffix: str) -> bool:
  8. """
  9. Returns whether `path` ends in `suffix`, ignoring case.
  10. """
  11. if not isinstance(path, str):
  12. path = str(path)
  13. return path.casefold().endswith(suffix.casefold())
  14. def files_from_file_or_dir(
  15. file_or_dir_path: pathlib.Path | str, predicate: typing.Callable[[pathlib.Path], bool] = lambda _: True
  16. ) -> list[pathlib.Path]:
  17. """
  18. Gets the files in `file_or_dir_path` satisfying `predicate`.
  19. If `file_or_dir_path` is a file, the single file is considered. Otherwise, all files in the directory are
  20. considered.
  21. :param file_or_dir_path: Path to a file or directory.
  22. :param predicate: Predicate to determine if a file is included.
  23. :return: A list of files.
  24. """
  25. if not isinstance(file_or_dir_path, pathlib.Path):
  26. file_or_dir_path = pathlib.Path(file_or_dir_path)
  27. selected_files = []
  28. def process_file(file_path: pathlib.Path):
  29. if predicate(file_path):
  30. selected_files.append(file_path)
  31. if file_or_dir_path.is_dir():
  32. for root, _, files in os.walk(file_or_dir_path):
  33. for file in files:
  34. file_path = pathlib.Path(root, file)
  35. process_file(file_path)
  36. else:
  37. process_file(file_or_dir_path)
  38. return selected_files