# scripts/powershell-backend-auto-venv.ps1 # 用途:在 Cursor/VS Code 集成终端中,cd 进入 backend 时自动激活 .venv,离开时 deactivate。 # 依赖:backend/.venv(由 python -m venv .venv 创建)。 # 逻辑:由 .vscode/settings.json 的 PowerShell (HXOPS) 终端配置在启动时 dot-source 本脚本。 $ErrorActionPreference = 'Stop' $script:HxopsWorkspaceRoot = Split-Path -Parent $PSScriptRoot $script:HxopsBackendRoot = Join-Path $script:HxopsWorkspaceRoot 'backend' $script:HxopsVenvActivate = Join-Path $script:HxopsBackendRoot '.venv\Scripts\Activate.ps1' # 判断当前路径是否位于 backend 目录或其子目录内。 # 核心逻辑:规范化路径后做前缀匹配,避免大小写与斜杠差异。 function Test-HxopsInBackendTree { param([string]$Path) if ([string]::IsNullOrWhiteSpace($Path)) { return $false } $normalized = [System.IO.Path]::GetFullPath($Path).TrimEnd('\', '/') $backendNormalized = [System.IO.Path]::GetFullPath($script:HxopsBackendRoot).TrimEnd('\', '/') return ($normalized -ceq $backendNormalized) -or $normalized.StartsWith("$backendNormalized\") } # 根据当前工作目录同步 backend/.venv 的激活状态。 # 核心逻辑:进入 backend 树且未激活则 source Activate.ps1;离开且当前 venv 属于本项目则 deactivate。 function Update-HxopsBackendVenv { if (-not (Test-Path -LiteralPath $script:HxopsVenvActivate)) { return } $inBackend = Test-HxopsInBackendTree -Path $PWD.Path $venvRoot = if ($env:VIRTUAL_ENV) { [System.IO.Path]::GetFullPath($env:VIRTUAL_ENV).TrimEnd('\', '/') } else { $null } $expectedVenv = [System.IO.Path]::GetFullPath( (Join-Path $script:HxopsBackendRoot '.venv') ).TrimEnd('\', '/') if ($inBackend) { if ($venvRoot -ne $expectedVenv) { . $script:HxopsVenvActivate } return } if ($venvRoot -eq $expectedVenv) { if (Get-Command deactivate -ErrorAction SilentlyContinue) { deactivate } } } # 保留用户原有 prompt,仅在每次显示提示符前同步 venv 状态(覆盖 cd / Set-Location 等所有改目录方式) if (Test-Path -Path Function:\prompt) { $script:HxopsOriginalPrompt = (Get-Item Function:\prompt).ScriptBlock } else { $script:HxopsOriginalPrompt = { "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " } } function global:prompt { Update-HxopsBackendVenv & $script:HxopsOriginalPrompt } Update-HxopsBackendVenv