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