参照文章 www.jianshu.com/p/4aa01c35b… ,稍作修改,完成了发包到钉钉群的代码。 主要是添加了git log。废话不多说。 主要是蒲公英中文处理不太好,直接在通知到钉钉的时候,加上了git log。
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
class ContentModel{
String text
String title
String picUrl
String messageUrl
}
/**
* 上传apk到蒲公英
*/
def uploadApk(def path, def apiKey, def pwd) {
//查找上传的apk文件,这里需要换成自己apk路径
def apkDir = new File(path)
if (!apkDir.exists()) {
throw new RuntimeException("apk output path not exists!")
}
def apk = null
for (int i = apkDir.listFiles().length - 1; i >= 0; i--) {
File file = apkDir.listFiles()[i]
if (file.name.endsWith(".apk")) {
apk = file
break
}
}
if (apk == null) {
throw new RuntimeException("apk file not exists!")
}
println "*************** start upload file ***************"
def twoHyphens = "--"
def boundary = "*********"
def end = "\r\n"
//模拟表单上传 multipart/form-data
def conn = new URL("https://www.pgyer.com/apiv2/app/upload").openConnection()
conn.setRequestMethod('POST')
conn.setRequestProperty("Connection", "Keep-Alive")
conn.setRequestProperty("Charset", "UTF-8")
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary)
conn.setDoInput(true)
conn.setDoOutput(true)
//添加参数:_api_key
def sb = new StringBuilder()
sb.append(twoHyphens).append(boundary).append(end)
sb.append("Content-Disposition: form-data; name=_api_key")
sb.append(end).append(end)
sb.append(apiKey).append(end)
// def desc = "${proc.in.text}"
//添加参数:buildUpdateDescription 更新日志,取值gradle.properties中的 BUILD_NOTES
sb.append(twoHyphens).append(boundary).append(end)
sb.append("Content-Disposition: form-data; name=buildUpdateDescription")
sb.append(end).append(end)
sb.append("This is Test").append(end)
//安装方式,密码安装
sb.append(twoHyphens).append(boundary).append(end)
sb.append("Content-Disposition: form-data; name=buildInstallType")
sb.append(end).append(end)
sb.append("2").append(end)
//安装密码
sb.append(twoHyphens).append(boundary).append(end)
sb.append("Content-Disposition: form-data; name=buildPassword")
sb.append(end).append(end)
sb.append(pwd).append(end)
//添加参数file: 需要上传的apk文件
sb.append(twoHyphens).append(boundary).append(end)
sb.append("Content-Disposition: form-data; name=file;filename=").append(apk.getName())
sb.append(end).append(end)
def dos = new DataOutputStream(conn.getOutputStream())
dos.writeBytes(sb.toString())
dos.flush()
sb.delete(0, sb.length())
def fis = new FileInputStream(apk)
byte[] bf = new byte[8192]
int len
while ((len = fis.read(bf)) != -1) {
dos.write(bf, 0, len)
}
sb.append(end)
sb.append(twoHyphens).append(boundary).append(end)
dos.writeBytes(sb.toString())
dos.flush()
fis.close()
dos.close()
conn.connect()
def text = conn.getContent().text
def resp = new JsonSlurper().parseText(text)
println text
println "*************** upload finish ***************"
if (resp.code != 0) {
throw new RuntimeException(resp.message)
}
println resp
// //浏览器中打开短连接
// def url = "https://www.pgyer.com/" + resp.data.buildShortcutUrl
// exec {
// commandLine "bash", "start", url
// }
sendMsgToDing(resp.data, apiKey, pwd)
}
//打包测试环境apk 上传蒲公英 发送邮件功能使用蒲公英自带的邮件功能
task packageDingTalk {
def apkDir = new File("./build/outputs/apk/debug")
if(apkDir.exists() && apkDir.isDirectory()){
apkDir.deleteDir()
}
dependsOn("assembleDebug")
doLast {
uploadApk("./build/outputs/apk/debug","蒲公英apikey", "蒲公英安装密码")
}
}
task packageReleaseDingTalk {
def apkDir = new File("./release")
if(apkDir.exists() && apkDir.isDirectory()){
apkDir.deleteDir()
}
dependsOn("assembleRelease")
doLast {
uploadApk("./release","蒲公英apikey", "蒲公英安装密码")
}
}
def sendMsgToDing(def data, def apiKey, def pwd){
def conn = new URL("钉钉机器人地址").openConnection()
conn.setRequestMethod('POST')
conn.setRequestProperty("Connection", "Keep-Alive")
conn.setRequestProperty("Content-type", "application/json;charset=UTF-8")
conn.setConnectTimeout(30000)
conn.setReadTimeout(30000)
conn.setDoInput(true)
conn.setDoOutput(true)
def dos = new DataOutputStream(conn.getOutputStream())
HashMap<String,Object> map = new HashMap<>()
map.put("msgtype", "link")
ContentModel contentModel = new ContentModel()
def command = """git log -3 --pretty=format:'%s' --abbrev-commit"""// Create the String
def proc = command.execute() // Call *execute* on the string
proc.waitFor() // Wait for the command to finish
// Obtain status and output
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
def k = proc.in.text.replaceAll("'","").replaceAll("\n",";")
println "stdout: ${k}" // *out* from the external program is *in* for groovy
contentModel.text = k
contentModel.title= "你的title"
contentModel.picUrl = data.buildQRCodeURL
contentModel.messageUrl= "https://www.pgyer.com/apiv2/app/install?_api_key=" + apiKey + "&buildKey="+data.buildKey+"&buildPassword="+pwd
map.put("link",contentModel)
def json = JsonOutput.toJson(map)
println(json)
dos.writeBytes(json)
def input = new BufferedReader(new InputStreamReader(conn.getInputStream()))
String line =""
String result=""
while ((line = input.readLine()) != null) {
result += line
}
dos.flush()
dos.close()
input.close()
conn.connect()
println(result)
}