Skip to content

Commit 45a2360

Browse files
authored
CM-37517 - Properly handle permission denied exception (#233)
1 parent 0533c7d commit 45a2360

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

cycode/cli/utils/path_utils.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
from functools import lru_cache
44
from typing import AnyStr, List, Optional
55

6-
from binaryornot.check import is_binary
6+
from binaryornot.helpers import is_binary_string
7+
8+
from cycode.cyclient import logger
79

810

911
@lru_cache(maxsize=None)
@@ -22,8 +24,28 @@ def get_absolute_path(path: str) -> str:
2224
return os.path.abspath(path)
2325

2426

27+
def _get_starting_chunk(filename: str, length: int = 1024) -> Optional[bytes]:
28+
# We are using our own implementation of get_starting_chunk
29+
# because the original one from binaryornot uses print()...
30+
31+
try:
32+
with open(filename, 'rb') as f:
33+
return f.read(length)
34+
except IOError as e:
35+
logger.debug('Failed to read the starting chunk from file: %s', filename, exc_info=e)
36+
37+
return None
38+
39+
2540
def is_binary_file(filename: str) -> bool:
26-
return is_binary(filename)
41+
# Check if the file extension is in a list of known binary types
42+
binary_extensions = ('.pyc',)
43+
if filename.endswith(binary_extensions):
44+
return True
45+
46+
# Check if the starting chunk is a binary string
47+
chunk = _get_starting_chunk(filename)
48+
return is_binary_string(chunk)
2749

2850

2951
def get_file_size(filename: str) -> int:
@@ -56,6 +78,8 @@ def get_file_content(file_path: str) -> Optional[AnyStr]:
5678
return f.read()
5779
except (FileNotFoundError, UnicodeDecodeError):
5880
return None
81+
except PermissionError:
82+
logger.warn('Permission denied to read the file: %s', file_path)
5983

6084

6185
def load_json(txt: str) -> Optional[dict]:

0 commit comments

Comments
 (0)