p4 Git Command Guide
The git p4 command provides bidirectional integration between Git and Perforce repositories. It enables cloning from Perforce depots, synchronizing changes, and submitting Git commits back to Perforce, supporting hybrid development workflows during migration.
git p4 Syntax:
Section titled “git p4 Syntax:”git p4 clone [<sync-options>] [<clone-options>] <p4-depot-path>...git p4 sync [<sync-options>] [<p4-depot-path>...]git p4 rebasegit p4 submit [<submit-options>] [<master-branch-name>]Core Operations:
Section titled “Core Operations:”Repository Operations:
Section titled “Repository Operations:”| Command | Description |
|---|---|
clone <depot-path> | Create Git repo from Perforce depot |
sync [<depot-path>] | Sync latest changes from Perforce |
rebase | Sync and rebase current branch |
submit [<branch>] | Submit Git commits to Perforce |
Understanding Perforce Integration:
Section titled “Understanding Perforce Integration:”Architecture Overview:
Section titled “Architecture Overview:”Perforce Server (p4d)├── Depot: //depot/project/│ ├── main/│ ├── release/│ └── dev/└── Metadata: changelists, workspaces, labels
Git Repository (git p4)├── Remote: p4 (tracks Perforce state)├── Branch: p4/main (mirrors Perforce main)├── Branch: p4/release (mirrors Perforce release)└── Local branches: feature/*, bugfix/*Change Mapping:
Section titled “Change Mapping:”Perforce Changelist → Git Commit├── Changelist number → Commit message prefix├── User → Author/Committer├── Timestamp → Commit date├── Files → Changed files└── Description → Commit messageBasic Usage Examples:
Section titled “Basic Usage Examples:”Cloning from Perforce:
Section titled “Cloning from Perforce:”# Clone entire depotgit p4 clone //depot/project
# Clone specific pathgit p4 clone //depot/project/main
# Clone with branch detectiongit p4 clone --detect-branches //depot/project
# Clone with custom destinationgit p4 clone //depot/project my-projectSynchronizing Changes:
Section titled “Synchronizing Changes:”# Sync latest changesgit p4 sync
# Sync specific depot pathgit p4 sync //depot/project/main
# Sync with verbose outputgit p4 sync --verbose
# Sync and rebase current branchgit p4 rebaseSubmitting to Perforce:
Section titled “Submitting to Perforce:”# Submit current branchgit p4 submit
# Submit specific branchgit p4 submit release-branch
# Submit with dry rungit p4 submit --dry-run
# Submit with custom changelistgit p4 submit --prepare-p4-onlyAdvanced Perforce Integration Scenarios:
Section titled “Advanced Perforce Integration Scenarios:”Branch-Aware Cloning:
Section titled “Branch-Aware Cloning:”# Clone with automatic branch detectiongit p4 clone --detect-branches //depot/project
# Result: Creates branches for each Perforce branch# - p4/main (from //depot/project/main)# - p4/release (from //depot/project/release)# - p4/dev (from //depot/project/dev)
# Set up tracking branchesfor branch in main release dev; do git checkout -b "$branch" "p4/$branch" git branch --set-upstream-to="p4/$branch" "$branch"doneSelective Synchronization:
Section titled “Selective Synchronization:”# Sync only specific changelistsgit p4 sync --max-changelist 12345
# Sync from specific changelistgit p4 sync --changesfile changes.txt
# Sync with custom client specgit p4 sync --use-client-spec
# Sync excluding certain filesgit p4 sync --exclude-path "/build/**"Migration Workflow:
Section titled “Migration Workflow:”#!/bin/bash# Complete Perforce to Git migration
migrate_to_git() { local p4_depot="$1" local git_repo="$2"
echo "Migrating $p4_depot to Git repository $git_repo"
# Initial clone git p4 clone "$p4_depot" "$git_repo" cd "$git_repo"
# Set up Git configuration git config user.name "Migration Bot" git config user.email "migration@example.com"
# Convert Perforce branches to Git branches git p4 sync --detect-branches
# Clean up Perforce-specific files find . -name "*.p4ignore" -delete rm -f .p4config
# Create Git ignore file cat > .gitignore << EOF# Build artifactsbuild/dist/
# IDE files.vscode/.idea/
# OS files.DS_StoreThumbs.dbEOF
# Initial Git commit git add . git commit -m "Initial migration from Perforce
Depot: $p4_depotMigrated: $(date)Tool: git p4"
echo "Migration complete. Repository ready for Git workflow."}
migrate_to_git "//depot/myproject" "my-git-repo"Hybrid Development Setup:
Section titled “Hybrid Development Setup:”# Set up hybrid Perforce/Git workflowsetup_hybrid_workflow() { local p4_depot="$1"
echo "Setting up hybrid workflow for $p4_depot"
# Clone from Perforce git p4 clone "$p4_depot"
# Create Git branches for different workflows git checkout -b feature-development git checkout -b hotfix git checkout -b experimental
# Set up sync automation cat > sync-from-p4.sh << 'EOF'#!/bin/bashecho "Syncing from Perforce..."git checkout p4/maingit p4 syncgit checkout feature-developmentgit rebase p4/mainecho "Sync complete"EOF
cat > submit-to-p4.sh << 'EOF'#!/bin/bashecho "Submitting to Perforce..."git checkout p4/maingit merge feature-developmentgit p4 submitecho "Submission complete"EOF
chmod +x sync-from-p4.sh submit-to-p4.sh
echo "Hybrid workflow setup complete" echo "Use sync-from-p4.sh to get Perforce changes" echo "Use submit-to-p4.sh to send Git changes to Perforce"}
setup_hybrid_workflow "//depot/hybrid-project"Configuration and Best Practices:
Section titled “Configuration and Best Practices:”Perforce Connection Setup:
Section titled “Perforce Connection Setup:”# Configure Perforce connectionexport P4PORT="perforce.example.com:1666"export P4USER="your-username"export P4CLIENT="your-workspace"
# Or use .p4config filecat > .p4config << EOFP4PORT=perforce.example.com:1666P4USER=your-usernameP4CLIENT=your-workspaceP4PASSWD=your-passwordEOF
# Test connectionp4 infoGit P4 Configuration:
Section titled “Git P4 Configuration:”# Configure git p4 behaviorgit config git-p4.user "Your Name"git config git-p4.email "your.email@example.com"git config git-p4.detectCopies truegit config git-p4.detectRenames true
# Configure submit behaviorgit config git-p4.skipSubmitEdit truegit config git-p4.preserveUser truegit config git-p4.allowSubmit "main|release/*"Performance Optimization:
Section titled “Performance Optimization:”# Optimize for large repositoriesgit config git-p4.maxChanges 1000git config git-p4.syncFromOrigin false
# Use compressiongit config core.compression 9git config pack.compression 9
# Configure parallel operationsexport P4_MAX_RESULTS=100000export P4COMMANDFLAGS="-z tag"Integration with Development Workflows:
Section titled “Integration with Development Workflows:”CI/CD Pipeline Integration:
Section titled “CI/CD Pipeline Integration:”#!/bin/bash# CI/CD pipeline with Perforce sync
ci_pipeline_with_p4() { echo "CI/CD pipeline with Perforce integration"
# Sync latest changes from Perforce git p4 sync --quiet
# Check for new changes if git diff --quiet p4/main; then echo "No new changes from Perforce" exit 0 fi
# Rebase current branch git p4 rebase
# Run tests if ! run-tests.sh; then echo "Tests failed" exit 1 fi
# Submit successful changes back to Perforce if [ "$CI_COMMIT_REF_NAME" = "main" ]; then git p4 submit --quiet echo "Changes submitted to Perforce" fi}
ci_pipeline_with_p4Release Management:
Section titled “Release Management:”# Release management with Perforcerelease_with_p4() { local version="$1" local branch="${2:-main}"
echo "Creating release $version from branch $branch"
# Ensure branch is up to date git checkout "$branch" git p4 rebase
# Create release tag git tag -a "v$version" -m "Release v$version
Created from Perforce branch: $branchPerforce changelist: $(git log --oneline -1 | cut -d' ' -f1)"
# Submit release to Perforce git p4 submit "$branch"
# Push Git changes git push origin "$branch" --tags
echo "Release $version created and synchronized"}
release_with_p4 "2.1.0" "release"Conflict Resolution:
Section titled “Conflict Resolution:”# Handle conflicts between Git and Perforceresolve_p4_conflicts() { echo "Resolving conflicts between Git and Perforce"
# Attempt automatic rebase if git p4 rebase; then echo "✓ Automatic rebase successful" return 0 fi
echo "Manual conflict resolution required"
# Show conflicting files git status
# For each conflict, choose resolution strategy for file in $(git diff --name-only --diff-filter=U); do echo "Resolving conflict in: $file"
# Option 1: Keep Git version # git checkout --theirs "$file"
# Option 2: Keep Perforce version # git checkout --ours "$file"
# Option 3: Manual merge echo "Please resolve conflict in $file manually" read -p "Press enter when resolved..."
git add "$file" done
# Complete rebase git rebase --continue
# Submit resolved changes git p4 submit
echo "Conflict resolution complete"}
resolve_p4_conflictsTroubleshooting Common Issues:
Section titled “Troubleshooting Common Issues:”Connection Problems:
Section titled “Connection Problems:”# Test Perforce connectionp4 info
# Check credentialsp4 login -s
# Verify depot accessp4 depotsp4 files //depot/project/...
# Debug connection issuesexport P4DEBUG=1git p4 clone //depot/project 2>&1 | head -50Synchronization Issues:
Section titled “Synchronization Issues:”# Check sync statusgit statusgit log --oneline p4/main..HEAD
# Force resyncgit p4 sync --force
# Check for missing changelistsgit p4 sync --verbose | grep "changelist"
# Reset p4 remotegit update-ref refs/remotes/p4/main <commit-hash>Submit Failures:
Section titled “Submit Failures:”# Check submit statusgit status
# Verify submit permissionsp4 protects //depot/project/...
# Check for open filesp4 opened
# Debug submit processgit p4 submit --dry-run --verbose
# Force submit (use carefully)git p4 submit --forceBranch Mapping Issues:
Section titled “Branch Mapping Issues:”# Check branch mappingsgit branch -r | grep p4/
# Manually map branchesgit p4 sync //depot/project/releasegit checkout -b release p4/release
# Fix branch detectiongit p4 sync --detect-branchesPerformance Issues:
Section titled “Performance Issues:”# Monitor sync performancetime git p4 sync
# Optimize for large depotsgit config git-p4.maxChanges 500git config git-p4.keepEmptyCommits false
# Use shallow sync for testinggit p4 sync --max-changelist 1000Real-World Usage Examples:
Section titled “Real-World Usage Examples:”Enterprise Migration Strategy:
Section titled “Enterprise Migration Strategy:”#!/bin/bash# Enterprise Perforce to Git migration strategy
enterprise_migration() { local p4_depot="$1" local migration_team="$2"
echo "Enterprise migration: $p4_depot" echo "Migration team: $migration_team"
# Phase 1: Assessment echo "Phase 1: Repository assessment" assess_repository "$p4_depot"
# Phase 2: Pilot migration echo "Phase 2: Pilot migration" pilot_migration "$p4_depot" "pilot-project"
# Phase 3: Team training echo "Phase 3: Team training and workflow setup" setup_team_workflows "$migration_team"
# Phase 4: Full migration echo "Phase 4: Full migration" full_migration "$p4_depot"
# Phase 5: Post-migration support echo "Phase 5: Post-migration monitoring" setup_monitoring "$p4_depot"}
assess_repository() { local depot="$1" echo "Assessing repository size and complexity..."
# Get depot statistics p4 sizes "$depot/..." | tail -1
# Count changelists p4 changes "$depot/...@2023/01/01,@now" | wc -l
# Identify branches p4 branches | grep -i "$depot"
echo "Assessment complete"}
pilot_migration() { local depot="$1" local project="$2"
echo "Pilot migration for $project"
# Migrate small project first git p4 clone "$depot/$project"
# Test Git workflows cd "$project" git checkout -b feature-test echo "test change" > test.txt git add test.txt git commit -m "Test commit" git p4 submit cd ..
echo "Pilot migration successful"}
setup_team_workflows() { local team="$1"
echo "Setting up workflows for team: $team"
# Create workflow documentation cat > git-p4-workflow.md << 'EOF'# Git-P4 Workflow Guide
## Daily Workflow1. Sync from Perforce: `git p4 rebase`2. Create feature branch: `git checkout -b feature/name`3. Make changes and commit4. Sync again: `git p4 rebase`5. Submit to Perforce: `git p4 submit`
## Branch Strategy- main: Mirrors Perforce main branch- feature/*: Git-only feature branches- release/*: Release preparation branches
## Best Practices- Always sync before starting work- Use descriptive commit messages- Test changes before submitting- Communicate with team about large changesEOF
echo "Workflow documentation created"}
full_migration() { local depot="$1"
echo "Full migration of $depot"
# Migrate all projects p4 depots | while read depot_info; do depot_name=$(echo "$depot_info" | awk '{print $2}') if [[ "$depot_name" == *project* ]]; then echo "Migrating $depot_name" git p4 clone --detect-branches "$depot_name" fi done
echo "Full migration complete"}
setup_monitoring() { local depot="$1"
echo "Setting up post-migration monitoring"
# Create monitoring script cat > monitor-migration.sh << EOF#!/bin/bash# Monitor Git-P4 migration health
echo "Migration Health Report - $(date)"
# Check sync statusecho "Sync status:"git p4 sync --dry-run 2>&1 | head -10
# Check for driftp4_last=$(p4 changes "$depot/...@2023/01/01,@now" | head -1 | awk '{print $2}')git_last=$(git log --oneline -1 | cut -d' ' -f1)
echo "Perforce latest: $p4_last"echo "Git latest: $git_last"
if [ "$p4_last" != "$git_last" ]; then echo "WARNING: Repositories have diverged!"else echo "✓ Repositories are synchronized"fiEOF
chmod +x monitor-migration.sh
# Schedule monitoring echo "0 * * * * $(pwd)/monitor-migration.sh" | crontab -
echo "Monitoring setup complete"}
enterprise_migration "//depot/company" "dev-team"Gradual Migration Approach:
Section titled “Gradual Migration Approach:”# Gradual migration maintaining Perforce as source of truthgradual_migration() { local p4_depot="$1" local git_repo="$2"
echo "Setting up gradual migration"
# Create Git mirror git p4 clone "$p4_depot" "$git_repo"
# Set up automated sync cat > sync-from-perforce.sh << EOF#!/bin/bashcd "$git_repo"echo "Syncing from Perforce at $(date)"git p4 sync --quietgit p4 rebase --quietecho "Sync complete"EOF
# Schedule regular sync (crontab -l ; echo "*/30 * * * * $(pwd)/sync-from-perforce.sh") | crontab -
# Create team migration guide cat > migration-guide.md << EOF# Gradual Migration to Git
## Current State- Perforce remains source of truth- Git repository is read-only mirror- Changes must be made in Perforce
## Migration Phases1. **Learning Phase**: Teams learn Git workflows2. **Hybrid Phase**: Some teams use Git, others Perforce3.. **Migration Phase**: Teams gradually move to Git4. **Completion Phase**: Perforce retired
## How to Contribute1. Sync latest changes: \`git p4 rebase\`2. Create feature branch: \`git checkout -b feature/name\`3. Make changes and commit4. Submit via Perforce interface (for now)5. Delete Git branch after Perforce submit
## Tools Available- \`sync-from-perforce.sh\`: Sync latest changes- \`git p4 rebase\`: Update current branch- \`git p4 sync\`: Sync without rebasingEOF
echo "Gradual migration setup complete" echo "See migration-guide.md for team instructions"}
gradual_migration "//depot/legacy-project" "git-mirror"Compliance and Audit Integration:
Section titled “Compliance and Audit Integration:”# Compliance workflow with audit trailscompliance_workflow() { local project="$1" local auditor="$2"
echo "Setting up compliance workflow for $project"
# Create audit branch git checkout -b audit-trail
# Set up audit logging cat > audit-submit.sh << EOF#!/bin/bashecho "Audit: Submit initiated by $(whoami) at $(date)" >> audit.log
# Capture current stateecho "Pre-submit state:" >> audit.loggit status --porcelain >> audit.loggit log --oneline -5 >> audit.log
# Perform submit with loggingif git p4 submit --verbose >> audit.log 2>&1; then echo "Audit: Submit successful" >> audit.log echo "✓ Changes submitted and audited"else echo "Audit: Submit failed" >> audit.log echo "✗ Submit failed - check audit.log" exit 1fi
# Notify auditormail -s "P4 Submit Audit" "$auditor" < audit.logEOF
chmod +x audit-submit.sh
# Set up pre-submit checks cat > pre-submit-checks.sh << EOF#!/bin/bashecho "Running pre-submit compliance checks..."
# Check for sensitive filesif find . -name "*.key" -o -name "*password*" | grep -q .; then echo "ERROR: Sensitive files detected" exit 1fi
# Check commit messagesif git log --oneline p4/main..HEAD | grep -i "temp\|test\|draft"; then echo "ERROR: Non-production commits detected" exit 1fi
# Check file sizesif find . -type f -size +100M | grep -q .; then echo "ERROR: Large files detected (>100MB)" exit 1fi
echo "✓ All compliance checks passed"EOF
chmod +x pre-submit-checks.sh
echo "Compliance workflow setup complete" echo "Run pre-submit-checks.sh before submitting" echo "Use audit-submit.sh for compliant submissions"}
compliance_workflow "regulated-project" "auditor@company.com"What’s the difference between git p4 and p4 git?
Section titled “What’s the difference between git p4 and p4 git?”git p4 is Git’s tool for Perforce integration; p4 git is Perforce’s Git integration. git p4 is more feature-rich and commonly used for migrations.
Can git p4 handle large Perforce repositories?
Section titled “Can git p4 handle large Perforce repositories?”Yes, with proper configuration. Use —max-changelist for partial imports, configure timeouts, and consider incremental migration strategies.
How do I handle Perforce branches with git p4?
Section titled “How do I handle Perforce branches with git p4?”Use —detect-branches to automatically create Git branches for Perforce branches. Manually map branches if detection doesn’t work.
What happens to Perforce metadata in Git?
Section titled “What happens to Perforce metadata in Git?”Changelist numbers become commit message prefixes, users map to Git authors, timestamps are preserved. File metadata is converted to Git equivalents.
Can I use git p4 without Perforce client?
Section titled “Can I use git p4 without Perforce client?”No, git p4 requires p4 command-line client and server access. Configure P4PORT, P4USER, and P4CLIENT environment variables.
How do I handle merge conflicts with git p4?
Section titled “How do I handle merge conflicts with git p4?”Resolve conflicts in Git, then use git p4 submit. For complex conflicts, consider using Perforce’s merge tools or manual resolution.
What’s the performance impact of git p4 sync?
Section titled “What’s the performance impact of git p4 sync?”Depends on repository size and network. Initial clone can be slow; incremental syncs are faster. Use —max-changelist for testing.
Can git p4 work with Perforce streams?
Section titled “Can git p4 work with Perforce streams?”Limited support. Use traditional depot paths for best compatibility. Some stream features may not translate perfectly to Git.
How do I migrate Perforce jobs and fixes?
Section titled “How do I migrate Perforce jobs and fixes?”Jobs become Git commit messages, fixes are tracked as commit relationships. Use git notes or custom tooling for complex job tracking.
What’s the relationship between git p4 and Git-LFS?
Section titled “What’s the relationship between git p4 and Git-LFS?”Compatible but separate. Use Git LFS in Git repository for large files; Perforce handles large files differently.
Can I use git p4 in CI/CD pipelines?
Section titled “Can I use git p4 in CI/CD pipelines?”Yes, configure Perforce credentials and use git p4 sync/rebase in pipelines. Be careful with submit operations in automated environments.
How do I handle Perforce file types in Git?
Section titled “How do I handle Perforce file types in Git?”Most file types work fine. Binary files, symlinks, and special Perforce types are handled appropriately. Test with your specific file types.
What’s the licensing impact of using git p4?
Section titled “What’s the licensing impact of using git p4?”git p4 is part of Git (GPL2). Perforce client tools have their own licensing. Check Perforce license for your use case.
Can git p4 handle Perforce triggers?
Section titled “Can git p4 handle Perforce triggers?”No direct support. Triggers must be handled separately or disabled during Git operations. Plan trigger management during migration.
How do I rollback a git p4 submit?
Section titled “How do I rollback a git p4 submit?”Use Perforce tools to rollback changelist, then resync Git repository. Avoid this by testing thoroughly before submitting.
What’s the difference between git p4 rebase and git p4 sync?
Section titled “What’s the difference between git p4 rebase and git p4 sync?”git p4 sync updates remote tracking branches; git p4 rebase does sync plus rebases current branch onto updated remote.
Can I use git p4 with multiple Perforce depots?
Section titled “Can I use git p4 with multiple Perforce depots?”Yes, specify multiple depot paths to git p4 clone/sync. Creates separate remote tracking branches for each depot.
Applications of the git p4 command
Section titled “Applications of the git p4 command”- Repository Migration: Migrate from Perforce to Git with full history preservation
- Hybrid Development: Support teams using both Perforce and Git during transition
- Bidirectional Sync: Keep Perforce and Git repositories synchronized
- Branch Management: Handle complex Perforce branching in Git workflows
- Enterprise Integration: Support large organizations migrating version control systems
- Compliance Workflows: Maintain audit trails during version control transitions