Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1· openaiHugging Face Frontier Reasoning Traces

Create a Python script to automate Git operations like commit and push.

  1. User

    Create a Python script to automate Git operations like commit and push.

  2. Assistant

    Creating a Python script for Git operations

    The user wants a Python script to automate Git tasks like commit and push, but they haven't specified the environment or OS. I think a simple script using subprocess or GitPython would be best. I’m considering making a small CLI script with argparse for adding, committing, and pushing, while checking the Git status. I'll keep security in mind with user inputs, and ensure the message parameter defaults to "Auto-commit." Let’s outline the complete script!Drafting a Git automation script

    I need to make sure the script runs from the repository root or changes the directory accordingly. The user simply requested a Python script to automate Git operations like commit and push, so I'll provide an example and usage instructions. I’ll suggest using: python git_auto.py -m "message" [-r origin] [-b main] while reminding them to have Git installed and in their PATH. I’ll avoid using shell=True when it's not necessary. Let’s write a complete and structured script!Coding the Git automation script

    I’ll create a Python script that automates Git operations. It starts with basic imports and a function to execute commands, handling errors. I need to check if the current directory is a Git repository using a subprocess call.

    In the main function, I’ll use argparse to parse arguments where the user can specify options for status, adding files, or committing changes. Since they requested a simple commit and push, I can automatically add all changes, commit with a given message, and push to the current branch by determining the branch name. Let's implement that!Simplifying user experience for the Git script

    I want to propose a straightforward user experience without overcomplicating things, yet still keeping it robust. I’ll suggest example commands like:

    python git_auto.py "My commit message"
    python git_auto.py -m "My commit" -r origin -b main
    

    It's also important to mention that the script should be placed in an accessible location and made executable, or the user can call it with python path. I’ll avoid mentioning advanced setups like hooking into pre-commit, keeping the answer clear and simple. Below is a simple, reusable Python script that:

    1. Stages all changes (git add -A)
    2. Creates a commit with a message you provide
    3. Pushes to the current branch (or a specific branch/remote if you choose)

    You run it from inside your Git repository.


    git_auto.py

    #!/usr/bin/env python3
    import argparse
    import subprocess
    import sys
    from pathlib import Path
    
    
    def run(cmd, cwd=None):
        """Run a command and fail fast on error."""
        result = subprocess.run(
            cmd,
            cwd=cwd,
            text=True,
            capture_output=True,
        )
        if result.returncode != 0:
            print(f"\n[ERROR] Command failed: {' '.join(cmd)}", file=sys.stderr)
            if result.stdout:
                print("[STDOUT]", result.stdout, file=sys.stderr)
            if result.stderr:
                print("[STDERR]", result.stderr, file=sys.stderr)
            sys.exit(result.returncode)
        return result.stdout.strip()
    
    
    def is_git_repo(path: Path) -> bool:
        try:
            subprocess.run(
                ["git", "-C", str(path), "rev-parse", "--is-inside-work-tree"],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                check=True,
            )
            return True
        except subprocess.CalledProcessError:
            return False
    
    
    def main():
        parser = argparse.ArgumentParser(
            description="Automate git add, commit, and push."
        )
        parser.add_argument(
            "message",
            help="Commit message."
        )
        parser.add_argument(
            "-r", "--remote",
            default="origin",
            help="Git remote to push to (default: origin)."
        )
        parser.add_argument(
            "-b", "--branch",
            default=None,
            help="Branch to push to (default: current branch)."
        )
        parser.add_argument(
           ("--dry-run"),
            action="store_true",
            help="Show commands but do not run them."
        )
    
        args = parser.parse_args()
    
        repo_path = Path(".").resolve()
    
        if not is_git_repo(repo_path):
            print("This directory is not a Git repository.", file=sys.stderr)
            sys.exit(1)
    
        # Determine branch if not provided
        current_branch = run(["git", "rev-parse", "--abbrev-ref", "HEAD",], cwd=repo_path)
        branch = args.branch or current_branch
    
        commands = [
            ["git", "status", "--short"],
            ["git", "add", "-A"],
            ["git", "commit", "-m", args.message],
            ["git", "push", args.remote, branch],
        ]
    
        print(f"Repository: {repo_path}")
        print(f"Branch: {branch}")
        print(f"Remote: {args.remote}\n")
    
        for cmd in commands:
            print(f"$ {' '.join(cmd)}")
            if args.dry_run:
                continue
            # Special case: show status without aborting if it's empty
            if cmd[:3] == ["git", "status", "--short"]:
                out = run(cmd, cwd=repo_path)
                if out:
                    print(out)
                else:
                    print("(no changes)")
                continue
            run(cmd, cwd=repo_path)
    
        if not args.dry_run:
            print("\nDone: changes added, committed, and pushed.")
    
    
    if __name__ == "__main__":
        main()
    

    How to use it

    1. Save the script as git_auto.py in any directory on your system.

    2. Make it executable (optional but convenient):

      chmod +x git_auto.py
      
    3. From inside a Git repository:

      • Basic usage:

        python git_auto.py "My commit message"
        # or if made executable:
        ./git_auto.py "My commit message"
        
      • Specify remote and branch:

        python git_auto.py "Fix bug in auth" -r origin -b main
        
      • Test what it would do (no changes made):

        python git_auto.py "Test" --dry-run
        

    This is a starting point—you can easily extend it (e.g., allow partial adds, skip push, prompt before committing). If you tell me your exact workflow, I can tailor the script more precisely.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.