-
Notifications
You must be signed in to change notification settings - Fork 0
/
harden.py
59 lines (48 loc) · 2.11 KB
/
harden.py
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
import subprocess
import os
from transformers import pipeline
# Constants
REPO_PATH = ' ' # Path to local git repository
COMMIT_MESSAGE = 'Another automatic improvement'
def update_repository(repo_path):
""" Pull the latest changes from the remote repository. """
subprocess.run(['git', 'pull'], cwd=repo_path, check=True)
def analyze_code(repo_path):
""" Analyze the code in the repository and suggest improvements. """
# Load a code review model from Hugging Face
reviewer = pipeline("code-review", model="microsoft/codebert-base-mlm-code-review")
# List all python files in the repository
improvements = {}
for root, _, files in os.walk(repo_path):
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
code = f.read()
# Analyze the code
result = reviewer(code)
improvements[file_path] = result['suggestions']
return improvements
def apply_improvements(improvements):
""" Apply suggested improvements to the code. """
for file_path, suggestions in improvements.items():
with open(file_path, 'r') as f:
code = f.readlines()
# Naive approach: replace line with suggestion if available
for suggestion in suggestions:
line_number = suggestion['line_number'] - 1 # Convert to 0-based index
code[line_number] = suggestion['suggestion']
with open(file_path, 'w') as f:
f.writelines(code)
def git_commit_and_push(repo_path, commit_message):
""" Commit the changes and push them to the remote repository. """
subprocess.run(['git', 'add', '.'], cwd=repo_path, check=True)
subprocess.run(['git', 'commit', '-m', commit_message], cwd=repo_path, check=True)
subprocess.run(['git', 'push'], cwd=repo_path, check=True)
def main():
update_repository(REPO_PATH)
improvements = analyze_code(REPO_PATH)
apply_improvements(improvements)
git_commit_and_push(REPO_PATH, COMMIT_MESSAGE)
if __name__ == "__main__":
main()