forked from cycodehq/cycode-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath_utils.py
More file actions
74 lines (49 loc) · 2.11 KB
/
Copy pathpath_utils.py
File metadata and controls
74 lines (49 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from typing import Iterable, List, Optional
import pathspec
import os
from pathlib import Path
from binaryornot.check import is_binary
def get_relevant_files_in_path(path: str, exclude_patterns: Iterable[str]) -> List[str]:
absolute_path = get_absolute_path(path)
if not os.path.isfile(absolute_path) and not os.path.isdir(absolute_path):
raise FileNotFoundError(f'the specified path was not found, path: {path}')
if os.path.isfile(absolute_path):
return [absolute_path]
directory_files_paths = _get_all_existing_files_in_directory(absolute_path)
file_paths = set({str(file_path) for file_path in directory_files_paths})
spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, exclude_patterns)
exclude_file_paths = set(spec.match_files(file_paths))
return [file_path for file_path in (file_paths - exclude_file_paths) if os.path.isfile(file_path)]
def is_sub_path(path: str, sub_path: str) -> bool:
try:
common_path = os.path.commonpath([get_absolute_path(path), get_absolute_path(sub_path)])
return path == common_path
except ValueError:
# if paths are on the different drives
return False
def get_absolute_path(path: str) -> str:
if path.startswith('~'):
return os.path.expanduser(path)
return os.path.abspath(path)
def is_binary_file(filename: str) -> bool:
return is_binary(filename)
def get_file_size(filename: str) -> int:
return os.path.getsize(filename)
def get_path_by_os(filename: str) -> str:
return filename.replace('/', os.sep)
def _get_all_existing_files_in_directory(path: str):
directory = Path(path)
return directory.rglob(r"*")
def is_path_exists(path: str):
return os.path.exists(path)
def get_file_dir(path: str) -> str:
return os.path.dirname(path)
def join_paths(path: str, filename: str) -> str:
return os.path.join(path, filename)
def get_file_content(file_path: str) -> Optional[str]:
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
return content
except FileNotFoundError:
return None