需求
把之前某个代码分支的每一次提交,都启动 Jenkins 编译一次。
获取代码历史提交记录
切换分支
git checkout -b master
查看历史提交记录
git log --pretty=oneline>gitlog.txt #将历史记录保存在 gitlog.txt 文件中,用文本编辑器修改,只保存每行一条 commit ID
提交记录倒序处理
通过 git log 输出的日志是从最近的一次提交开始的,如果我们需要按照时间顺序由早到近的编译,则需要将 gitlog.txt 文件进行倒序处理。处理 python 脚本 reverse_order.py 如下:
#!/usr/bin/python3
#coding:utf-8
f = open("gitlog.txt", "r")
lines = f.readlines()
rows = len(lines)
for num in range(rows-1,-1,-1):
print(lines[num].strip())
f.close()
python3 reverse_order.py>reverse_gitlog.txt
Jenkins API
下载 jenkins-cli.jar
打开 http://172.0.0.1:8080/cli/(也就是Jenkins地址后面加/cli)
启动脚本
将 jenkins-cli.jar 和 Jenkins 启动脚本放在同一目录下,当然你的服务器上应该有 Java 环境脚本才能正常运行。
假设你的 Jenkins project 是参数构建,而且有2个参数,一个是 GERRIT_BRANCH ,一个是 COMMIT_ID 。如图:
循环编译 shell 脚本如下:
#!/bin/bash
for id in `cat reverse_gitlog.txt`
do
echo $id
java -jar jenkins-cli.jar -s http://172.0.0.1:8080/ -auth $user:$passwd -webSocket build $job_name -s -p GERRIT_BRANCH=master -p COMMIT_ID=${id}
sleep 5
done
节省了大量时间,不用一个接一个的手动去点击 build 。
官方描述
java -jar jenkins-cli.jar -s http://172.0.0.1:8080/ -webSocket build JOB [-c] [-f] [-p] [-r N] [-s] [-v] [-w]
Starts a build, and optionally waits for a completion.
Aside from general scripting use, this command can be used to invoke another job from within a build of one job.
With the -s option, this command changes the exit code based on the outcome of the build (exit code 0 indicates a success) and interrupting the command will interrupt the job.
With the -f option, this command changes the exit code based on the outcome of the build (exit code 0 indicates a success) however, unlike -s, interrupting the command will not interrupt the job (exit code 125 indicates the command was interrupted).
With the -c option, a build will only run if there has been an SCM change.
JOB : Name of the job to build
-c : Check for SCM changes before starting the build, and if there's no
change, exit without doing a build (default: false)
-f : Follow the build progress. Like -s only interrupts are not passed
through to the build. (default: false)
-p : Specify the build parameters in the key=value format. (default: {})
-s : Wait until the completion/abortion of the command. Interrupts are passed
through to the build. (default: false)
-v : Prints out the console output of the build. Use with -s (default: false)
-w : Wait until the start of the command (default: false)
END >-<