Jenkins Active Choices Reactive Parameter无法显示指定默认分支
问题根因
你的默认选中逻辑不生效有三个核心原因:
- 函数调用时未开启选中标记逻辑:你定义的
getAllBranches方法第三个参数activeChoice默认值为false,但最后调用方法时仅传入了仓库地址、凭证ID两个参数,导致给master分支追加:selected选中标记的代码块从未执行。 - 异常分支返回值格式错误:当凭证查询失败、命令执行报错时,你直接返回了字符串类型的错误信息,Active Choices插件会把字符串拆分为单个字符作为下拉选项,破坏整体渲染逻辑。
- (可选冗余问题)拉取分支的命令带了
-t参数,会同时拉取仓库标签,标签的refs/tags/前缀没有被过滤,会混入分支选项列表。
修正步骤
- 调整方法调用传参,将
activeChoice参数显式设为true,触发默认选中逻辑 - 把所有错误场景的返回值统一包裹为列表格式,避免插件解析异常
- (按需)移除
git ls-remote命令的-t参数,只拉取正式分支数据,过滤标签 - 额外增加兜底逻辑:如果指定的默认分支不存在于拉取到的分支列表中,直接将默认分支插入到列表首位作为兜底
修正后完整代码
import com.cloudbees.plugins.credentials.CredentialsProvider; import jenkins.model.Jenkins def git_url ="url" def targetCredentialId = "efa7bed9-56a0-42ac-8fa3-a68fe7700801" def getAllBranches(url, credentialID, activeChoice = false, defaultBranch = 'master') { def jenkinsCredentials = CredentialsProvider.lookupCredentials( com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey, Jenkins.instance ); def key = jenkinsCredentials.findResult { it.id == credentialID ? it.privateKey : null } if( !key ) { return ['Error: credentials not found'] } // 移除-t参数,仅拉取分支,不拉取标签;如果需要展示标签可保留-t Process process = ['ssh-agent','bash','-c', "echo '" + key + "' | ssh-add - 2> /dev/null && git ls-remote -h " + url].execute() def out = new StringBuilder() def err = new StringBuilder() process.consumeProcessOutput( out, err ) process.waitFor() if( err.size() > 0 ) return [err.toString()] if( out.size() > 0 ) { def branches = out.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') } // 去重,避免异常重复分支 branches = branches.unique() if( activeChoice ) { def defaultBranchIndex = branches.indexOf(defaultBranch) if( defaultBranchIndex >= 0 ) { branches.set(defaultBranchIndex, defaultBranch + ':selected') } else { // 兜底:如果没找到默认分支,直接插入到列表首位设为选中 branches.add(0, defaultBranch + ':selected') } } return branches } return ['Error: no branch found'] } // 第三个参数传true,开启active choice选中标记逻辑 return getAllBranches(git_url, targetCredentialId, true)
配置校验项
改完代码后需要确认以下插件配置,避免渲染异常:
- Active Choices Reactive Parameter的选项类型选择
Single Select(单选下拉),如果使用多选Multi Select,上述:selected标记逻辑同样生效 - 不要勾选
Omit value field选项,否则插件无法解析选中标记 - 配置保存后首次打开构建页面,建议硬刷新浏览器(Ctrl+F5 / Command+Shift+R)清除旧的参数缓存,即可看到master分支默认被选中
内容的提问来源于stack exchange,提问作者nadavlevin
相关产品推荐
相关产品推荐

