如何将Jenkins机器中的report文件夹提交至git的gh-pages分支
问题:将Jenkins生成的HTML报告提交至git的gh-pages分支
现有Jenkins流水线的Commit Report阶段脚本如下:
stage('Commit Report') { steps { sh 'ls -l' // commit and push the generated HTML report to git withCredentials([usernamePassword(credentialsId: 'abc123', passwordVariable: 'password', usernameVariable: 'username')]) { sh """ // some gitconfig command git checkout -b gh-pages origin/gh-pages || git checkout --orphan gh-pages // copy and add report folder into this branch git commit -a -m "Automated commit: HTML report" git fetch origin gh-pages git merge -s recursive -X theirs origin/gh-pages git push origin gh-pages """ } } }
执行sh 'ls -l'后,当前工作目录存在report文件夹(包含HTML报告):
18:08:39 total 28 18:08:39 -rw-r--r--. 1 build 1000680000 3320 Sep 6 11:57 jenkinsfile 18:08:39 -rw-r--r--. 1 build 1000680000 3601 Sep 6 11:57 pom.xml 18:08:39 -rw-r--r--. 1 build 1000680000 10565 Sep 6 11:57 portalTest.iml 18:08:39 -rw-r--r--. 1 build 1000680000 1139 Sep 6 11:57 README.md 18:08:39 drwxr-sr-x. 4 build 1000680000 80 Sep 6 12:08 report 18:08:39 drwxr-sr-x. 4 build 1000680000 30 Sep 6 11:57 src 18:08:39 drwxrwsrwx. 8 build 1000680000 140 Sep 6 12:08 target 18:08:39 -rw-r--r--. 1 build 1000680000 837 Sep 6 11:57 testng.xml
需要修改脚本,将report文件夹及其内容复制到gh-pages分支并完成提交推送。
解决方案:修改后的Jenkins流水线脚本
以下是调整后的完整Commit Report阶段代码,确保report文件夹正确提交到gh-pages分支:
stage('Commit Report') { steps { sh 'ls -l' withCredentials([usernamePassword(credentialsId: 'abc123', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) { sh """ # 配置git提交身份,避免身份验证失败 git config --global user.name "Jenkins CI" git config --global user.email "jenkins@your-domain.com" # 记录当前工作分支,操作完成后切回 CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) # 处理gh-pages分支:远程存在则拉取最新代码,不存在则创建孤儿分支 if git ls-remote --exit-code origin gh-pages; then git checkout gh-pages git pull origin gh-pages else git checkout --orphan gh-pages # 孤儿分支需先提交初始内容才能推送 git rm -rf . echo "HTML report branch" > README.md git add README.md git commit -m "Initial commit: Setup gh-pages branch" fi # 从原分支复制report文件夹到gh-pages分支 git checkout \$CURRENT_BRANCH -- report/ # 添加并提交report文件夹,带时间戳便于区分版本 git add report/ git commit -m "Automated commit: Update HTML report (\$(date +'%Y-%m-%d %H:%M:%S'))" # 安全推送至远程gh-pages分支 git push https://\${GIT_USERNAME}:\${GIT_PASSWORD}@github.com/your-username/your-repo.git gh-pages # 切回原工作分支,不影响后续流水线步骤 git checkout \$CURRENT_BRANCH """ } } }
关键修改说明
- git身份配置:添加
git config命令,解决Jenkins提交时出现的author identity unknown错误。 - 备份当前分支:用
CURRENT_BRANCH变量记录当前工作分支,操作完成后切回,避免影响后续流水线任务。 - gh-pages分支处理:
- 先检查远程是否存在gh-pages分支,存在则拉取最新代码确保同步;
- 不存在则创建孤儿分支,并提交初始文件(孤儿分支无历史提交,必须先完成一次提交才能推送)。
- 复制report文件夹:通过
git checkout $CURRENT_BRANCH -- report/直接从原分支复制目录,避免手动拷贝的路径问题。 - 安全推送:使用凭证变量构造带权限的git URL,既保证推送权限,又避免明文暴露密码。
- 切回原分支:操作完成后切回原工作分支,确保流水线后续步骤在正确分支执行。
内容的提问来源于stack exchange,提问作者Wani M
相关产品推荐
相关产品推荐

