jenkins pipeline 检查子模块分支/CommitId是否正确
·
检查子模块分支/CommitId是否正确
script {
// 1. 获取子模块状态
// --recursive 确保检查嵌套子模块
def status = sh(script: "git submodule status --recursive", returnStdout: true).trim()
echo "子模块当前状态:\n${status}"
// 2. 定义你期望的校验规则
// 假设要求子模块 'my-api-docs' 必须指向 commit '7a1b2c3'
def expectedSubmodule = "my-api-docs"
def expectedCommitPrefix = "7a1b2c3"
// 3. 遍历输出行进行校验
def lines = status.split('\n')
def found = false
for (line in lines) {
// 正则匹配:[空格/+-] [CommitID] [路径] [括号里的分支/标签]
// 这里的正则匹配:开头可能是空格、+或-,接着是 commit id,然后是路径
if (line.contains(expectedSubmodule)) {
found = true
// 提取 Commit ID (前 7 位)
def actualCommit = line.trim().split(' ')[0].replaceAll(/[+-]/, "")
if (!actualCommit.startsWith(expectedCommitPrefix)) {
error "【校验失败】子模块 ${expectedSubmodule} 的 Commit ID 为 ${actualCommit},不符合预期值 ${expectedCommitPrefix}"
}
echo "【校验通过】子模块 ${expectedSubmodule} 匹配成功"
}
}
if (!found) {
error "【校验失败】在项目中未找到子模块: ${expectedSubmodule}"
}
}
分支
script {
def subPath = "lib/common-utils" // 子模块路径
def expectedBranch = "develop"
// 进入子模块目录执行命令
dir(subPath) {
def currentBranch = sh(script: "git rev-parse --abbrev-ref HEAD", returnStdout: true).trim()
if (currentBranch != expectedBranch) {
// 如果处于 Detached HEAD,rev-parse 会返回 "HEAD"
error "【分支错误】子模块 ${subPath} 当前在 ${currentBranch},预期应在 ${expectedBranch}"
}
}
}
更多推荐

所有评论(0)