阿里云主机折上折
  • 微信号
Current Site:Index > Multi-working directory management

Multi-working directory management

Author:Chuan Chen 阅读数:48925人阅读 分类: 开发工具

The Necessity of Multiple Working Directory Management

Git, as a distributed version control system, by default associates each repository with a single working directory. However, in actual development, there's often a need to simultaneously handle multiple related projects or different branches of the same project. The traditional approach involves cloning separate repositories for each project, but this leads to wasted disk space and synchronization difficulties. Multiple working directory management significantly improves development efficiency by supporting multiple working directories from a single repository.

Git Worktree Basics

Git version 2.5+ introduced the worktree feature, allowing multiple linked working directories for the same repository. Each working directory can check out different branches while sharing the same .git repository.

# Create a new working directory
git worktree add ../feature-branch feature/login

This command creates a new workspace in the ../feature-branch directory and checks out the feature/login branch. The original repository and working directories share the object database but maintain independent indexes and working trees.

Typical Use Cases

Parallel Development of Different Features

Suppose you're developing a payment feature when suddenly an urgent login bug fix is needed:

# Main workspace
~/project (main) $ git worktree add ../hotfix-login

# New terminal
cd ../hotfix-login
git checkout -b hotfix/login-issue
# After fixing
git commit -m "Fix login validation issue"
git push origin hotfix/login-issue

Simultaneously Viewing Different Versions

Need to compare implementation differences between v1.0 and v2.0:

git worktree add ../v1.0-release v1.0
git worktree add ../v2.0-release v2.0

Long-Running Branch Maintenance

For demo environment branches that need to run long-term:

git worktree add ../demo-env demo/2023-10
# This directory can maintain the demo environment continuously

Advanced Management Techniques

Listing All Worktrees

git worktree list
# Sample output:
/path/to/main      abcd123 [main]
/path/to/feature   efgh456 [feature/login]

Cleaning Up Deleted Worktrees

git worktree prune

Locking Worktrees to Prevent Accidental Operations

git worktree lock ../legacy-support

Comparison with Submodules

Feature Worktree Submodules
Repository Relation Same repository Different repositories
Update Method Automatic synchronization Requires explicit update
Disk Usage Shared object store Completely independent
Use Case Multiple branches of same project Combination of different projects

Practical Example in Frontend Projects

Modern frontend projects often require running different environments simultaneously:

// package.json
{
  "scripts": {
    "dev:main": "cd ../main-worktree && npm run dev",
    "dev:feature": "cd ../feature-worktree && npm run dev"
  }
}

Using tools like PM2 to manage development servers across multiple workspaces:

pm2 start "npm run dev:main" --name main-app
pm2 start "npm run dev:feature" --name feature-app

Common Problem Solutions

Worktree Occupancy Issues

When trying to delete an occupied worktree:

git worktree remove ../stale-worktree --force

Branch Conflict Handling

If two worktrees accidentally check out the same branch:

fatal: 'feature/login' is already checked out at '/path/to/other/worktree'

The solution is to explicitly specify a new worktree path or use different branches.

Remote Repository Operations

All worktrees share the same remote configuration but can set different push targets:

git config remote.origin.push HEAD:refs/heads/feature/login

Automation Management Scripts

Creating worktree management tool scripts (Node.js example):

const { execSync } = require('child_process')

function addWorktree(name, branch) {
  const path = `../${name}`
  try {
    execSync(`git worktree add ${path} ${branch}`)
    console.log(`Created worktree at ${path} for branch ${branch}`)
  } catch (err) {
    console.error(`Error creating worktree: ${err.message}`)
  }
}

// Example: Create worktrees for each feature branch
const features = ['auth', 'payment', 'profile']
features.forEach(feat => {
  addWorktree(`feat-${feat}`, `feature/${feat}`)
})

IDE Integration Configuration

Efficiently managing multiple worktrees in VS Code:

  1. Create a workspace file project-multi.code-workspace:
{
  "folders": [
    {"path": "."},
    {"path": "../feature-auth"},
    {"path": "../feature-payment"}
  ],
  "settings": {
    "git.autoRepositoryDetection": "subFolders"
  }
}
  1. Configure debug launch items:
{
  "configurations": [
    {
      "name": "Main Server",
      "cwd": "${workspaceFolder:main}"
    },
    {
      "name": "Auth Feature",
      "cwd": "${workspaceFolder:feature-auth}"
    }
  ]
}

Performance Optimization Recommendations

For large repositories:

  1. Use SSD storage for worktrees
  2. Regularly perform garbage collection:
git gc --auto
  1. Limit the number of worktrees (typically no more than 5-7)
  2. Compress unused worktrees:
git worktree compress ../old-feature

Security Considerations

  1. Sensitive information appears in all worktrees
  2. .git directories may retain history after worktree deletion
  3. Recommended to set read-only permissions for production worktrees:
chmod -R a-w ../production-worktree

Cross-Platform Compatibility Handling

Path handling examples in Windows environment:

# Creating worktrees in PowerShell
git worktree add ..\feature-branch feature/login

# Handling spaces in paths
git worktree add "..\my feature" feature/login

Using worktrees in CI/CD pipelines:

steps:
  - name: Setup worktrees
    run: |
      git worktree add ../test $TEST_BRANCH
      cd ../test && npm ci

Historical Version Tracing

Using worktrees to view historical version states:

git worktree add ../v1.2.0 v1.2.0
cd ../v1.2.0
git show HEAD:src/index.js

Large Team Collaboration Patterns

Team conventions for worktree naming:

../<developer>-<jira-id>-<feature>
Example:
../zhang-APP-123-login
../li-APP-456-payment

Accompanying cleanup script:

# Clean worktrees unmodified for over 30 days
find ../* -maxdepth 0 -type d -mtime +30 | xargs git worktree remove

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.