<# .SYNOPSIS 提交前共享检查:推断变更文件所属模块,校验提交信息格式。 .DESCRIPTION 读取 git diff 中变更的文件,根据 hooks/commit-module-mappings.json 推断模块,然后校验提交信息是否符合 [模块][类型]: 描述 格式。 .PARAMETER Message 待校验的提交信息。 .EXAMPLE .\docs\hooks\commit-check.ps1 -Message "[entity][docs]: 补充实体池说明" #> param( [Parameter(Mandatory = $true)] [string]$Message ) $ErrorActionPreference = 'Stop' $mappingFile = Join-Path $PSScriptRoot 'commit-module-mappings.json' if (-not (Test-Path $mappingFile)) { Write-Error "Module mapping file not found: $mappingFile" exit 1 } $mapping = Get-Content $mappingFile -Raw | ConvertFrom-Json function Get-ChangedFiles { $staged = (cmd /c "git diff --cached --name-only 2>nul") -split "`r?`n" | Where-Object { $_ } if (-not $staged) { $staged = @() } $unstaged = (cmd /c "git diff --name-only 2>nul") -split "`r?`n" | Where-Object { $_ } if (-not $unstaged) { $unstaged = @() } $all = @($staged) + @($unstaged) | Select-Object -Unique | Where-Object { $_ } return $all } function Get-ModuleForFile($file) { foreach ($entry in $mapping.mappings) { if ($file -match $entry.pattern) { return $entry.module } } return $null } function Get-ModulesFromChangedFiles($files) { $modules = @() foreach ($file in $files) { $module = Get-ModuleForFile $file if ($module) { $modules += $module } } return $modules | Select-Object -Unique } function Test-CommitMessage($message, $modules) { if ($message -notmatch '^\[([^\]]+)\]\[([^\]]+)\]:\s*(.+)$') { return @{ IsValid = $false; Reason = '提交信息格式应为:[模块][类型]: 描述' } } $msgModule = $Matches[1] $msgType = $Matches[2] $msgDesc = $Matches[3] if (-not $msgDesc) { return @{ IsValid = $false; Reason = '提交信息缺少描述内容' } } if ($mapping.validTypes -notcontains $msgType) { return @{ IsValid = $false; Reason = "无效的类型 '$msgType'。有效类型:$($mapping.validTypes -join ', ')" } } if ($modules -and $modules -notcontains $msgModule) { Write-Warning "提交信息中的模块 [$msgModule] 与变更文件推断的模块 [$($modules -join ', ')] 不一致,请确认是否 intentional。" } return @{ IsValid = $true; Reason = '' } } $files = Get-ChangedFiles if (-not $files) { Write-Host "未检测到变更文件。" -ForegroundColor Yellow exit 0 } $modules = Get-ModulesFromChangedFiles $files Write-Host "变更文件:" $files | ForEach-Object { Write-Host " - $_" } if ($modules) { Write-Host "推断模块:$($modules -join ', ')" } else { Write-Warning "未能从变更文件推断出模块,请检查提交信息是否手动指定了正确模块。" } $result = Test-CommitMessage $Message $modules if (-not $result.IsValid) { Write-Error $result.Reason exit 1 } Write-Host "提交信息格式正确。" -ForegroundColor Green exit 0