Skip to main content

Git Integration

PraisonAI CLI provides deep Git integration for tracking changes, auto-committing with AI-generated messages, and managing your version control workflow seamlessly.

Overview

Git integration features:
  • Auto-commit - Commit with AI-generated messages
  • Diff viewing - Rich diff display with syntax highlighting
  • Undo support - Safely undo AI changes
  • Branch management - Create and switch branches
  • Stash support - Stash and restore changes

Quick Start

# In interactive mode
>>> /diff          # Show current changes
>>> /commit        # Commit with AI message
>>> /undo          # Undo last commit

# Or use Python API
from praisonai.cli.features import GitIntegrationHandler

handler = GitIntegrationHandler()
handler.initialize(repo_path=".")
handler.show_status()

CLI Commands

/diff

Show current changes:
>>> /diff
╭─────────────────────────────────────────────────╮
                   Changes
├─────────────────────────────────────────────────┤
 diff --git a/src/main.py b/src/main.py
 @@ -10,6 +10,8 @@
  def main():
 +    logger.info("Starting application")         
 +    config = load_config()                      
      app = Application()                         
╰─────────────────────────────────────────────────╯

/commit

Commit with AI-generated message:
>>> /commit
Analyzing changes...

Generated commit message:
  feat(main): Add logging and config loading

  - Added logger.info call at startup
  - Added config loading before app initialization

[C]ommit / [E]dit message / [A]bort? c

 Committed: abc1234 - feat(main): Add logging and config loading

/undo

Undo the last commit:
>>> /undo
Undo last commit: "feat(main): Add logging and config loading"?
[Y]es / [N]o? y

 Commit undone. Changes are now staged.

Python API

Basic Usage

from praisonai.cli.features import GitIntegrationHandler

# Initialize
handler = GitIntegrationHandler(verbose=True)
git = handler.initialize(repo_path="/path/to/repo")

# Check if it's a git repo
if git.is_repo:
    print("Git repository detected")

Status

# Get repository status
status = handler.show_status()

print(f"Branch: {status.branch}")
print(f"Staged files: {status.staged_files}")
print(f"Modified files: {status.modified_files}")
print(f"Untracked files: {status.untracked_files}")
print(f"Is clean: {status.is_clean}")

Diff

# Show diff
diff_content = handler.show_diff()

# Show staged diff only
staged_diff = handler.show_diff(staged=True)

# Get diff for specific file
file_diff = git.get_diff_content(file_path="src/main.py")

Commit

# Commit with auto-generated message
commit = handler.commit()
print(f"Committed: {commit.short_hash} - {commit.message}")

# Commit with custom message
commit = handler.commit(message="fix: resolve null pointer exception")

# Commit without auto-staging
commit = handler.commit(auto_stage=False)

Undo

# Undo last commit (soft reset - keeps changes staged)
success = handler.undo(soft=True)

# Hard undo (discards changes)
success = handler.undo(soft=False)

Log

# Show commit log
commits = handler.show_log(count=10)

for commit in commits:
    print(f"{commit.short_hash} {commit.message} ({commit.author})")

Git Manager

For more control, use GitManager directly:
from praisonai.cli.features.git_integration import GitManager

git = GitManager(repo_path="/path/to/repo")

# Stage files
git.stage_files(["src/main.py", "src/utils.py"])
git.stage_files()  # Stage all

# Create commit
commit = git.commit("feat: add new feature")

# Branch operations
git.create_branch("feature/new-feature")
git.checkout_branch("main")
branches = git.get_branches()

# Stash
git.stash(message="WIP: working on feature")
git.stash_pop()

# Undo
git.undo_last_commit(soft=True)

Commit Message Generation

Automatic Generation

from praisonai.cli.features.git_integration import CommitMessageGenerator

generator = CommitMessageGenerator(use_ai=False)

# Generate from diff
diff_content = git.get_diff_content(staged=True)
message = generator.generate(diff_content)

# With context
message = generator.generate(
    diff_content,
    context="Fixing the authentication bug",
    style="conventional"  # or "simple", "detailed"
)

Message Styles

Conventional (default):
feat(auth): Add password validation

- Added regex pattern for password strength
- Added error messages for weak passwords
Simple:
Add password validation
Detailed:
feat(auth): Add password validation

- Added regex pattern for password strength
- Added error messages for weak passwords

+45 -12 lines in 2 files

Diff Viewer

Rich Display

from praisonai.cli.features.git_integration import DiffViewer

viewer = DiffViewer()

# Display diff with syntax highlighting
viewer.display_diff(diff_content, title="My Changes")

# Display status
viewer.display_status(status)

# Display log
viewer.display_log(commits)

Output Example

╭─────────────────────────────────────────────────╮
│              📊 Git Status                       │
├─────────────────────────────────────────────────┤
│ Category      │ Files                           │
├───────────────┼─────────────────────────────────┤
│ Branch        │ main                            │
│ Staged        │ 2                               │
│ Modified      │ 1                               │
│ Untracked     │ 0                               │
│ Ahead/Behind  │ +1 / -0                         │
╰─────────────────────────────────────────────────╯

Integration with Autonomy Modes

Git operations respect autonomy settings:
from praisonai.cli.features import (
    GitIntegrationHandler,
    AutonomyModeHandler
)

autonomy = AutonomyModeHandler()
autonomy.initialize(mode="suggest")

git = GitIntegrationHandler()
git.initialize()

# In suggest mode, commit requires approval
# In auto_edit mode, commit is auto-approved
# In full_auto mode, all git operations are auto-approved

Best Practices

Safe Workflow

  1. Review diff first - Always check /diff before committing
  2. Use meaningful messages - Edit AI messages if needed
  3. Commit frequently - Small, focused commits
  4. Use branches - Create branches for experiments

Commit Message Guidelines

# Good: Specific and descriptive
"feat(api): Add rate limiting to /users endpoint"

# Bad: Vague
"Update code"

Undo Strategy

# Soft undo - keeps changes for editing
handler.undo(soft=True)

# Hard undo - only for discarding mistakes
handler.undo(soft=False)  # Use with caution!

Configuration

Environment Variables

# Default commit message style
export PRAISONAI_COMMIT_STYLE=conventional

# Auto-commit after AI changes
export PRAISONAI_AUTO_COMMIT=false

# Git author for AI commits
export PRAISONAI_GIT_AUTHOR="PraisonAI <[email protected]>"

Git Config

# Set up git for AI commits
git config user.name "Your Name"
git config user.email "[email protected]"

# Optional: Sign AI commits
git config commit.gpgsign true

Error Handling

from praisonai.cli.features.git_integration import GitManager

git = GitManager(repo_path="/path/to/repo")

# Check if repo exists
if not git.is_repo:
    print("Not a git repository")
    return

# Handle commit errors
commit = git.commit("message")
if commit is None:
    print("Commit failed - check for conflicts or empty changes")