Windows 环境下 Git Worktree 与 Python 虚拟环境自动化创建指南
因为 AI 可以多实例运行,所以在 Windows 环境下,我需要频繁地创建 Git Worktree 和 Python 虚拟环境来支持多个项目的开发。 为了提高效率,我让 AI 给了个解决办法,在创建新的 worktree 时自动化完成这些任务。
环境:
- Windows 11
- PowerShell 7.5
将下面的函数放到你的 $PROFILE 中,这样每次打开 PowerShell 都可以使用 gwa 命令来创建新的 worktree 和虚拟环境。
$PROFILE 是 PowerShell 的配置文件路径,通常位于 C:\Users\<YourUsername>\Documents\PowerShell\Microsoft.PowerShell_profile.ps1。
# 查看实际 profile 路径
$PROFILE
# 如果文件不存在就创建
if (!(Test-Path $PROFILE)) { New-Item -ItemType File -Path $PROFILE -Force }
# 用编辑器打开
notepad $PROFILE
# 放到 $PROFILE 里
function gwtadd {
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Path,
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]$Rest
)
# 1) 创建 worktree
git worktree add $Path @Rest
if ($LASTEXITCODE -ne 0) {
Write-Error "git worktree add failed."
return
}
# 2) 进入新目录
$fullPath = Resolve-Path $Path
Push-Location $fullPath
try {
# 3) 创建 venv
& "C:\Users\User\AppData\Local\Programs\Python\Python312\python.exe" -m venv .venv
if ($LASTEXITCODE -ne 0) {
Write-Error "venv creation failed."
return
}
# 4) 激活 venv(点源,确保当前 shell 生效)
. .\.venv\Scripts\Activate.ps1
# 5) 安装依赖(若存在 requirements.txt)
if (Test-Path .\requirements.txt) {
python -m pip install --upgrade pip
pip install -r requirements.txt
} else {
Write-Host "requirements.txt not found, skip pip install."
}
Write-Host "Worktree ready: $fullPath"
}
finally {
Pop-Location
}
}
Set-Alias gwa gwtadd
使用方法:
# 例如创建并切到新分支
gwa ..\gl-auto-test-core-feat -b feat/my-branch