refactor: improve code formatting and readability

This commit is contained in:
KaySar12 2025-05-27 17:35:30 +07:00
parent 29cdce86ea
commit 49a722e0a1

View File

@ -4,6 +4,7 @@ import sys
import psutil
from dotenv import load_dotenv
from interpreter import OpenInterpreter
load_dotenv()
commit = {}
@ -16,7 +17,8 @@ agent.auto_run = True
agent.verbose = False
agent.llm.temperature = 0.3
agent.code_output_sender = "assistant"
agent.messages=[]
agent.messages = []
def is_repo_spy_running():
"""Check if repo_spy is currently running."""
@ -32,12 +34,14 @@ def is_repo_spy_running():
pass
return False
def get_git_credentials():
if len(sys.argv) != 4:
print("Usage: python gen_commit.py <GIT_USER> <GIT_PASS> <PROJECT_PATH>")
sys.exit(1)
return sys.argv[1], sys.argv[2], sys.argv[3]
def get_git_diff(project_path, summary=True):
"""Run git diff and return the output."""
flag = "--compact-summary" if summary else ""
@ -48,20 +52,22 @@ def get_git_diff(project_path, summary=True):
all_changes = result.strip() + "\n" + staged_changes.strip()
return all_changes.strip() if all_changes.strip() else "✓ No changes"
def load_guide_content(filename: str) -> str:
"""Load guide content from resources directory."""
guide_path = os.path.join(os.path.dirname(__file__), "resources", filename)
with open(guide_path, "r") as f:
return f.read()
def gen_commit(project_path: str, **kwargs) -> str:
"""
Generate commit message using OpenInterpreter based on git diff output.
Args:
project_path (str): Path to git repository
**kwargs: Additional arguments including custom_prompt
Returns:
str: Generated commit message
"""
@ -69,9 +75,9 @@ def gen_commit(project_path: str, **kwargs) -> str:
guides = {
"convention": load_guide_content("commit_message_guide.md"),
"rules": load_guide_content("commit_convention_rules.md"),
"analysis": load_guide_content("diff_analysis_guide.md")
"analysis": load_guide_content("diff_analysis_guide.md"),
}
# Configure agent system message
agent.system_message = f"""
You are a helpful assistant that generates concise, conventional commit messages based on code diffs.
@ -88,7 +94,7 @@ def gen_commit(project_path: str, **kwargs) -> str:
- Analyze the git diff using this content to understand what changed.
{guides['analysis']}
"""
if repo_spy:
return get_spy_commit(project_path, agent, **kwargs)
@ -103,7 +109,12 @@ def gen_commit(project_path: str, **kwargs) -> str:
"""
response = agent.chat(prompt)
return response[-1]["content"].strip() if isinstance(response, list) and response else str(response).strip()
return (
response[-1]["content"].strip()
if isinstance(response, list) and response
else str(response).strip()
)
def get_spy_commit(project_path, agent: OpenInterpreter, **kwargs):
if not repo_spy:
@ -129,7 +140,7 @@ def get_spy_commit(project_path, agent: OpenInterpreter, **kwargs):
# Keep the most recent changes by taking the last MAX_LOG_SIZE characters
spy_log = spy_log[-MAX_LOG_SIZE:]
# Try to find a clean break point (newline)
first_newline = spy_log.find('\n')
first_newline = spy_log.find("\n")
if first_newline != -1:
spy_log = spy_log[first_newline:].strip()
@ -152,6 +163,7 @@ Summarize this git activity log and generate a commit message: {spy_log}
print(f"Error summarizing spy.log: {e}")
return None
async def has_submodules():
"""Check if the repository has any submodules."""
proc = await asyncio.create_subprocess_exec(
@ -401,19 +413,19 @@ async def push_code():
print("\nChanges to commit:")
for status, file_path in changes:
print(f"{status} {file_path}")
commit_msg = gen_commit(project_path)
if project_path not in commit:
commit[project_path] = commit_msg
else:
commit[project_path] += f"\n{commit_msg}"
confirmation = input(
f"\nCommit all changes?\n"
f"Commit message: {commit_msg}\n"
f"Options: (y)es, (n)o, (r)etry: "
).lower()
if confirmation in ["y", "yes"]:
await commit_changes(changes, project_path, remote_url, commit_msg)
if confirmation in ["r", "re", "retry"]: