Git Management
Git management is an essential part of AI Builder project development, providing version control, code collaboration, branch management, and more. A well-designed Git strategy ensures code quality, supports team collaboration, and makes version rollback easier.
Overview
AI Builder's Git management includes the following core features:
- 📝 Version control: track code changes and version history
- 🌿 Branch management: support multi-branch development and merge strategies
- 👥 Team collaboration: enable collaborative development and code reviews
- 🔄 Auto-sync: automatically synchronize code with cloud environments
- 🚀 CI/CD integration: continuous integration and automated deployment
Repository initialization
1. Create a repository
Initialize in AI Builder:
# AI Builder automatically creates a Git repository for the project
# Choose "Enable Git Management" when creating the project
Manually initialize a local repository:
# Enter your project directory
cd your-project
# Initialize Git repository
git init
# Add remote repository
git remote add origin https://github.com/your-username/your-project.git
# Set default branch
git branch -M main
# First commit
git add .
git commit -m "Initial commit: AI Builder project setup"
git push -u origin main
2. Repository structure
Standard project structure:
your-project/
├── .git/ # Git configuration directory
├── .gitignore # Ignore rules
├── README.md # Project documentation
├── package.json # Project dependencies
├── src/ # Source code
│ ├── components/ # Components
│ ├── pages/ # Pages
│ ├── utils/ # Utility functions
│ └── styles/ # Styles
├── functions/ # Cloud functions
│ ├── user/ # User-related functions
│ └── task/ # Task-related functions
├── database/ # Database configuration
├── docs/ # Documentation
└── tests/ # Tests
3. .gitignore configuration
Recommended .gitignore:
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Production builds
/dist
/build
*.tgz
*.tar.gz
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# IDE files
.vscode/
.idea/
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
# Temporary folders
tmp/
temp/
# CloudBase specific
.tcb_env
.cloudbase/
# AI Builder specific
.aibuilder/
*.aibuilder.cache
Branch management strategies
1. Git Flow
Main branches:
main/master: production branch, stable releasesdevelop: integration branch for latest featuresfeature/*: feature branches for new workrelease/*: release branches to prepare versionshotfix/*: hotfix branches for urgent fixes
Branch workflow example:
# Create and switch to develop
git checkout -b develop
# Create a feature branch
git checkout -b feature/user-authentication develop
# Merge feature into develop after completion
git checkout develop
git merge --no-ff feature/user-authentication
git branch -d feature/user-authentication
# Create a release branch
git checkout -b release/1.0.0 develop
# After release, merge into main and develop
git checkout main
git merge --no-ff release/1.0.0
git tag -a v1.0.0 -m "Release version 1.0.0"
git checkout develop
git merge --no-ff release/1.0.0
git branch -d release/1.0.0
2. GitHub Flow
Simplified flow:
# Create a feature branch from main
git checkout main
git pull origin main
git checkout -b feature/task-management
# Develop and commit
git add .
git commit -m "Add task creation functionality"
git push origin feature/task-management
# Create a Pull Request
# After code review, merge into main
# Delete feature branch
git checkout main
git pull origin main
git branch -d feature/task-management
3. Branch naming conventions
Feature branches:
feature/user-login
feature/task-management
feature/data-export
Fix branches:
bugfix/login-error
bugfix/data-validation
hotfix/security-patch
Release branches:
release/1.0.0
release/1.1.0
release/2.0.0-beta
Commit conventions
1. Commit message format
Conventional Commits:
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
Types:
feat: new featurefix: bug fixdocs: documentationstyle: formatting changesrefactor: code refactortest: testschore: build or tooling changes
Examples:
# New feature
git commit -m "feat(auth): add user login functionality"
# Bug fix
git commit -m "fix(task): resolve task deletion error"
# Docs
git commit -m "docs: update API documentation"
# Refactor
git commit -m "refactor(utils): optimize date formatting function"
# Breaking change
git commit -m "feat(api): change user authentication method
BREAKING CHANGE: API endpoint /auth/login now requires email instead of username"
2. Commit best practices
Commit often, keep changes small:
# Small incremental commits
git add src/components/TaskCard.js
git commit -m "feat(task): add task card component"
git add src/components/TaskCard.css
git commit -m "style(task): add task card styling"
git add src/pages/TaskList.js
git commit -m "feat(task): integrate task card in task list"
Pre-commit checks:
# Check status
git status
# Review changes
git diff
# Stage interactively
git add -p # interactive staging
# Run tests before commit
npm test
npm run lint
# Commit
git commit -m "feat(task): add task filtering functionality"
Collaboration
1. Pull Request process
Create a Pull Request:
# Push feature branch
git push origin feature/user-profile
# Create PR on GitHub/GitLab and fill PR template
PR template sample:
## Change description
### Features
- Add user profile page
- Implement avatar upload
- Support editing personal information
### Change type
- [ ] Bug fix
- [x] New feature
- [ ] Refactor
- [ ] Docs update
### Tests
- [x] Unit tests passed
- [x] Integration tests passed
- [x] Manual tests completed
### Screenshots

### Related Issue
Closes #123
### Checklist
- [x] Code follows project guidelines
- [x] Added necessary tests
- [x] Updated relevant documentation
- [x] All checks passed
2. Code review
Review focus:
// Good code example
const createTask = async (taskData) => {
// validate params
if (!taskData.title || taskData.title.trim() === '') {
throw new Error('Task title cannot be empty');
}
// process data
const task = {
...taskData,
id: generateId(),
createdAt: new Date(),
status: 'pending'
};
// save to database
return await db.collection('tasks').add(task);
};
// Code that needs improvement
const createTask = (data) => {
// missing validation
// missing error handling
// unclear variable names
let t = { ...data, id: Math.random() };
db.collection('tasks').add(t);
};
Review comment example:
## Review feedback
### Summary
Code is well-structured and functional. A few suggestions below:
### Specific suggestions
**src/components/TaskCard.js:25**
```suggestion
// Consider adding PropTypes validation
import PropTypes from 'prop-types';
TaskCard.propTypes = {
task: PropTypes.object.isRequired,
onEdit: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired
};
src/utils/dateFormat.js:10
// Consider a more robust date formatter
const formatDate = (date) => {
if (!date) return '';
return new Intl.DateTimeFormat('zh-CN').format(new Date(date));
};
Tests
Please add unit tests for the new TaskCard component.
Docs
Consider updating README.md with component usage.
### 3. Conflict resolution
**Handle merge conflicts**:
```bash
# Update local branch
git checkout feature/user-profile
git fetch origin
git rebase origin/main
# If conflicts occur, resolve them manually
# Edit conflict files and keep desired code
# Mark conflicts resolved
git add .
git rebase --continue
# Push updates
git push --force-with-lease origin feature/user-profile
Conflict example:
// Conflict content
<<<<<<< HEAD
const API_URL = 'https://api.production.com';
=======
const API_URL = 'https://api.staging.com';
>>>>>>> feature/user-profile
// Resolved
const API_URL = process.env.NODE_ENV === 'production'
? 'https://api.production.com'
: 'https://api.staging.com';
Versioning
1. Semantic versioning
Format: MAJOR.MINOR.PATCH
MAJOR: incompatible API changesMINOR: backward-compatible feature additionsPATCH: backward-compatible bug fixes
Examples:
# Bug fix
git tag v1.0.1
# New feature
git tag v1.1.0
# Major release
git tag v2.0.0
# Pre-release
git tag v1.1.0-beta.1
git tag v1.1.0-rc.1
2. Release management
Automated release script:
#!/bin/bash
# scripts/release.sh
set -e
# Get current version
CURRENT_VERSION=$(node -p "require('./package.json').version")
echo "Current version: $CURRENT_VERSION"
# Input new version
echo "Enter new version (current: $CURRENT_VERSION):"
read NEW_VERSION
# Validate version format
if ! [[ $NEW_VERSION =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Error: invalid version format"
exit 1
fi
# Update version
npm version $NEW_VERSION --no-git-tag-version
# Build project
echo "Building..."
npm run build
# Run tests
echo "Running tests..."
npm test
# Commit changes
git add .
git commit -m "chore: bump version to $NEW_VERSION"
# Create tag
git tag -a v$NEW_VERSION -m "Release version $NEW_VERSION"
# Push to remote
git push origin main
git push origin v$NEW_VERSION
echo "Release $NEW_VERSION completed!"
3. Changelog
CHANGELOG.md format:
# Changelog
All noteworthy changes to this project will be documented in this file.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
- User profile page
- Task labels
### Changed
- Improve task list performance
- Improve mobile responsiveness
### Fixed
- Fix login state issue
- Fix task deletion dialog display bug
## [1.1.0] - 2024-01-15
### Added
- Task categorization management
- Data export feature
- Dark theme support
### Changed
- Refactor authentication module
- Optimize database query performance
### Fixed
- Fix task due date display bug
- Fix file upload failure
### Removed
- Remove deprecated API endpoints
## [1.0.0] - 2024-01-01
### Added
- Initial release
- User registration and login
- Basic task management
- Responsive UI
CI/CD integration
1. GitHub Actions
Workflow config:
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
steps:
- uses: actions/checkout@v3
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run tests
run: npm test -- --coverage
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18.x'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build project
run: npm run build
- name: Upload build artifacts
uses: actions/upload-artifact@v3
with:
name: build-files
path: dist/
deploy:
needs: build
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- name: Download build artifacts
uses: actions/download-artifact@v3
with:
name: build-files
path: dist/
- name: Deploy to CloudBase
env:
TCB_ENV: ${{ secrets.TCB_ENV }}
TCB_SECRET_ID: ${{ secrets.TCB_SECRET_ID }}
TCB_SECRET_KEY: ${{ secrets.TCB_SECRET_KEY }}
run: |
npm install -g @cloudbase/cli
tcb login --apiKeyId $TCB_SECRET_ID --apiKey $TCB_SECRET_KEY
tcb hosting:deploy dist/ -e $TCB_ENV
tcb functions:deploy -e $TCB_ENV
2. Automated testing
Test config:
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
moduleNameMapping: {
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
'^@/(.*)$': '<rootDir>/src/$1'
},
collectCoverageFrom: [
'src/**/*.{js,jsx}',
'!src/index.js',
'!src/serviceWorker.js',
'!src/**/*.test.{js,jsx}'
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
}
};
Test scripts:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"test:ci": "jest --ci --coverage --watchAll=false"
}
}
FAQ
Q: How to handle large files in the repo?
A: Use Git LFS (Large File Storage) to manage large files and keep repository size manageable.
Q: Team members have inconsistent Git configurations. What to do?
A: Use .editorconfig and .gitattributes to enforce consistent formatting and configurations.
Q: How to roll back to a previous version?
A: Use git revert or git reset. For production environments, prefer git revert to preserve history.
Q: Too many branches causing confusion?
A: Regularly clean up merged branches, enforce naming conventions, and use branch protection rules.
Next steps
After configuring Git management, proceed to resource management and monitoring:
📊 Configure resource management →
Or go back to other parts of the development flow: