> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Git Integration

> Seamless Git operations with AI-generated commit messages

# 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

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
>>> /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:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
>>> /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:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
>>> /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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai.cli.features import GitIntegrationHandler

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

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

### Status

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Undo last commit (soft reset - keeps changes staged)
success = handler.undo(soft=True)

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

### Log

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Good: Specific and descriptive
"feat(api): Add rate limiting to /users endpoint"

# Bad: Vague
"Update code"
```

### Undo Strategy

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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 <ai@praison.ai>"
```

### Git Config

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Set up git for AI commits
git config user.name "Your Name"
git config user.email "you@example.com"

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

## Error Handling

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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")
```

## Related Features

* [Slash Commands](/docs/cli/slash-commands) - `/diff`, `/commit`, `/undo`
* [Autonomy Modes](/docs/cli/autonomy-modes) - Control git operation approval
* [Commit](/docs/cli/commit) - Detailed commit documentation
