cjuexuan / mynote

237 stars 34 forks source link

jenkins打包的正确姿势 #37

Open cjuexuan opened 7 years ago

cjuexuan commented 7 years ago

今天闲来无事,帮别人写了个脚本用来进行jenkins打包,免得在浏览器点来点去

虽然我们用了#24 gitlab ci,但ci我们现在只是特定分支去跑,有的时候还是需要在命令行手工触发的

所以用这个还是能节约一些时间的,代码如下

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
import requests
import sys
from bs4 import BeautifulSoup

print("choose a job to build")
# 填你常用job的名字
username = ""
password = ""
base_url = "http://{}:{}@jenkins.ximalaya.com".format(username, password)
jobs = ['spoor-stream', 'spoor-thirdparty-collect', 'spoor-dashboard', 'xql-product', 'xql-beta']
length = len(jobs)
jobs_menu = {i + 1: j for i, j in enumerate(jobs)}
for i, job in jobs_menu.items():
    print(i, job)
index = int(input("input index:\n"))
if index > length:
    print('index wrong!')
    sys.exit(1)
job = jobs_menu.get(index)
print('build {} now'.format(job))
job_url = base_url + '/job/' + job

def gettoken():
    token_url = base_url + '/me/configure'
    token_html = requests.get(token_url).text
    soup = BeautifulSoup(token_html, "html.parser")
    try:
        return soup.find(id='apiToken').get('value')
    except AttributeError:
        print('maybe username or password error')
        sys.exit(1)

def commit():
    build_result = check_status()
    token = gettoken()
    if build_result is None:
        print("job already in running")
        return False
    else:
        commit_url = "{}/build?token={}&delay=0sec".format(job_url, token)
        return requests.post(commit_url).ok

def check_status():
    check_status_url = job_url + "/lastBuild/api/json"
    result = requests.get(check_status_url).json()["result"]
    return result

def main():
    if commit():
        while check_status() is None:
            print("wait for job finish")
            time.sleep(5)
        print(check_status())
    else:
        print("failure commit")

if __name__ == '__main__':
    main()

将该文件放到path下面

输出

choose a job to build
0 spoor-stream
1 spoor-thirdparty-collect
2 spoor-dashboard
3 xql-product
4 xql-beta
input index:
1
build spoor-thirdparty-collect now
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
wait for job finish
SUCCESS