-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfilehelpfunctions.py
More file actions
136 lines (104 loc) · 4.27 KB
/
filehelpfunctions.py
File metadata and controls
136 lines (104 loc) · 4.27 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""
License GPLv3 or higher.
(C) 2025 Created by Maikel Mardjan - https://nocomplexity.com/
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Helper functions for files
"""
import ast
import os
import sys
import warnings
from pathlib import Path
def read_in_source_file(file_path):
# Ensure file_path is a Path object
file_path = Path(file_path)
if file_path.is_dir():
print(
"Error: The given path is a directory.\nUse 'codeaudit filescan' to security audit Python files in a directory or PyPI package.\nThe 'codeaudit modulescan' command works per file only, not on a directory.\nUse codeaudit -h for help"
)
sys.exit(1)
if file_path.suffix.lower() != ".py":
print("Error: The given file is not a Python (.py) file.")
sys.exit(1)
try:
with file_path.open("r", encoding="utf-8") as f:
return f.read()
except Exception as e:
print(f"Failed to read file: {e}")
sys.exit(1)
def collect_python_source_files(directory):
"""
Collects all Python source files (.py) from a directory, including subdirectories,
while skipping directories that are hidden (start with '.') or underscore-prefixed,
or are in a predefined exclusion list.
Args:
directory (str): The path to the directory to search.
Returns:
list: A list of absolute paths to valid Python source files.
"""
EXCLUDE_DIRS = {"docs", "docker", "dist", "tests"}
python_files = []
for root, dirs, files in os.walk(directory):
# Filter out unwanted directories
dirs[:] = [
d
for d in dirs
if not (d.startswith(".") or d.startswith("_") or d in EXCLUDE_DIRS)
]
for file in files:
if file.endswith(".py") and not file.startswith("."):
full_path = os.path.join(root, file)
if os.path.isfile(full_path):
python_files.append(os.path.abspath(full_path))
# check if the file can be parsed using the AST
final_file_list = []
for python_file in python_files:
if is_ast_parsable(python_file):
final_file_list.append(python_file)
else:
print(
f"Error: {python_file} will be skipped due to syntax error while parsing into AST."
)
return final_file_list
def get_filename_from_path(file_path):
"""
Extracts the file name (including extension) from a full path string.
Args:
file_path (str): The full path to the file.
Returns:
str: The file name.
"""
# return os.path.basename(file_path)
return Path(file_path).name
def is_ast_parsable(file_path):
"""
Checks whether a Python file can be parsed using the AST module.
Args:
file_path (str): Path to the Python source file.
Returns:
bool: True if the file can be parsed without syntax errors, False otherwise.
"""
try:
with open(file_path, "r", encoding="utf-8") as f:
source = f.read()
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=SyntaxWarning)
ast.parse(source, filename=file_path)
return True
except (SyntaxError, UnicodeDecodeError, ValueError) as e:
return False
def has_python_files(input_path):
"""
Check whether a directory contains at least one Python file.
Args:
input_path (str | Path): Path to a directory.
Returns:
bool: True if the directory contains at least one Python file, False otherwise.
"""
file_path = Path(input_path)
if not file_path.is_dir():
return False
files_to_check = collect_python_source_files(file_path)
return len(files_to_check) > 0