import os import sys import subprocess from dotenv import load_dotenv from interpreter import OpenInterpreter # 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 parse_cli_args(): """ Parse and validate command-line arguments. Returns: tuple: (git_user, git_pass, git_repo, project_path) """ if len(sys.argv) != 5: sys.exit("Usage: python gen_commit.py ") return sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] def run_shell_command(command, cwd=None): """ Execute a shell command and return the output. Args: command (str): Command to run. cwd (str): Optional working directory. Returns: str: Command output. """ try: result = subprocess.run( command, cwd=cwd, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) return result.stdout.strip() except subprocess.CalledProcessError as e: print(f"[ERROR] Command failed: {command}\n{e.stderr}") return "" def read_file(path): """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.llm.model = "gpt-4o" agent.auto_run = True convention = read_file(COMMIT_CONVENTION_PATH) git_commands = read_file(GIT_COMMANDS_PATH) agent.system_message = f""" Your name is Bifrost. You are a helpful assistant that generates commit messages based on uncommitted code. Rules: 1. Use English. 2. Follow this format: {convention} 3. Use these git commands to analyze changes: {git_commands} 4. Return only the commit message. No explanations or extra output. """ prompt = f""" cd {project_path} Check for uncommitted changes in the repository and generate a commit message accordingly. """ response = agent.chat(prompt) if isinstance(response, list): for item in reversed(response): if isinstance(item, dict) and "content" in item: return item["content"].strip() return str(response).strip() def commit_and_push_code(): """ Pull, generate commit message, commit changes, and push to remote repository. """ git_user, git_pass, git_repo, project_path = parse_cli_args() os.chdir(project_path) commit_msg = generate_commit_message(project_path) print(f"Generated Commit Message:\n{commit_msg}\n") remote_url = f"https://{git_user}:{git_pass}@{git_repo}" # Run Git commands run_shell_command(f"git pull {remote_url} || true") run_shell_command("git add .") run_shell_command(f'git commit -m "{commit_msg}" || true') run_shell_command(f"git push {remote_url} || true") if __name__ == "__main__": commit_and_push_code()