refactor: update gen_commit logic and naming conventions

Improve commit message generation logic and rename functions for clarity and consistency.
This commit is contained in:
2025-05-14 09:38:53 +07:00
parent 86eeef2a72
commit d31afa09e1
+64 -53
View File
@@ -4,21 +4,34 @@ import subprocess
from dotenv import load_dotenv from dotenv import load_dotenv
from interpreter import OpenInterpreter from interpreter import OpenInterpreter
load_dotenv() # Load environment variables from .env # Load environment variables from .env
load_dotenv()
# Constants
COMMIT_CONVENTION_PATH = os.path.join(os.path.dirname(__file__), "resources/commit_convention.md")
GIT_COMMANDS_PATH = os.path.join(os.path.dirname(__file__), "resources/git_commit.md")
def get_git_credentials(): def parse_cli_args():
"""Retrieve Git credentials and project path from command-line arguments.""" """
Parse and validate command-line arguments.
Returns:
tuple: (git_user, git_pass, git_repo, project_path)
"""
if len(sys.argv) != 5: if len(sys.argv) != 5:
print( sys.exit("Usage: python gen_commit.py <GIT_USER> <GIT_PASS> <GIT_REPO> <PROJECT_PATH>")
"Usage: python gen_commit.py <GIT_USER> <GIT_PASS> <GIT_REPO> <PROJECT_PATH>"
)
sys.exit(1)
return sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] return sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
def run_command(command, cwd=None): def run_shell_command(command, cwd=None):
"""Run a shell command and return the output.""" """
Execute a shell command and return the output.
Args:
command (str): Command to run.
cwd (str): Optional working directory.
Returns:
str: Command output.
"""
try: try:
result = subprocess.run( result = subprocess.run(
command, command,
@@ -31,82 +44,80 @@ def run_command(command, cwd=None):
) )
return result.stdout.strip() return result.stdout.strip()
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print(f"Command failed: {command}\n{e.stderr}") print(f"[ERROR] Command failed: {command}\n{e.stderr}")
return "" return ""
def gen_commit(project_path): def read_file(path):
"""Use OpenInterpreter to generate a commit message based on git diff.""" """Read the contents of a file."""
with open(path, "r", encoding="utf-8") as f:
return f.read()
def generate_commit_message(project_path):
"""
Use OpenInterpreter to generate a commit message based on the git diff.
Args:
project_path (str): Path to the project directory.
Returns:
str: Generated commit message.
"""
agent = OpenInterpreter() agent = OpenInterpreter()
agent.llm.model = "gpt-4o"
agent.auto_run = True agent.auto_run = True
# Read both convention and git commit files convention = read_file(COMMIT_CONVENTION_PATH)
convention_path = os.path.join( git_commands = read_file(GIT_COMMANDS_PATH)
os.path.dirname(__file__), "resources/commit_convention.md"
)
git_commit_path = os.path.join(os.path.dirname(__file__), "resources/git_commit.md")
with open(convention_path, "r") as f:
convention_content = f.read()
with open(git_commit_path, "r") as f:
git_commit_content = f.read()
agent.system_message = f""" agent.system_message = f"""
Your name is Bifrost. Your name is Bifrost.
You are a helpful assistant that generates commit messages based on uncommitted code. You are a helpful assistant that generates commit messages based on uncommitted code.
Follow these rules: Rules:
1. Use English. 1. Use English.
2. Be concise and follow this format: 2. Follow this format:
{convention_content} {convention}
3. Use these git commands to analyze changes as you see fit: 3. Use these git commands to analyze changes:
{git_commit_content} {git_commands}
4. Only return the commit message. Do not add explanation or extra output. 4. Return only the commit message. No explanations or extra output.
""" """
prompt = f""" prompt = f"""
Generate a commit message based on the following changes in the project directory:
First, change directory:
cd {project_path} cd {project_path}
Check for uncommitted changes in the repository and generate a commit message accordingly.
Then run:
git diff --name-status
Then generate a commit message according to the changes.
""" """
response = agent.chat(prompt) response = agent.chat(prompt)
# Extract just the content from the response if isinstance(response, list):
if isinstance(response, list) and len(response) > 0: for item in reversed(response):
if isinstance(response[-1], dict) and "content" in response[-1]: if isinstance(item, dict) and "content" in item:
return response[-1]["content"].strip() return item["content"].strip()
return str(response).strip() return str(response).strip()
def push_code(): def commit_and_push_code():
"""Pull, commit, and push code with AI-generated message.""" """
git_user, git_pass, git_repo, project_path = get_git_credentials() Pull, generate commit message, commit changes, and push to remote repository.
"""
git_user, git_pass, git_repo, project_path = parse_cli_args()
# Change to project path
os.chdir(project_path) os.chdir(project_path)
# Generate commit message commit_msg = generate_commit_message(project_path)
commit_msg = gen_commit(project_path) print(f"Generated Commit Message:\n{commit_msg}\n")
print(f"Generated commit message:\n{commit_msg}\n")
# Pull, add, commit, and push
remote_url = f"https://{git_user}:{git_pass}@{git_repo}" remote_url = f"https://{git_user}:{git_pass}@{git_repo}"
run_command(f"git pull {remote_url} || true") # Run Git commands
run_command("git add .") run_shell_command(f"git pull {remote_url} || true")
run_command(f'git commit -m "{commit_msg}" || true') run_shell_command("git add .")
run_command(f"git push {remote_url} || true") run_shell_command(f'git commit -m "{commit_msg}" || true')
run_shell_command(f"git push {remote_url} || true")
if __name__ == "__main__": if __name__ == "__main__":
push_code() commit_and_push_code()