背景
項目里面有一個公用的jar包,內(nèi)容是一些通用的處理邏輯,不同的業(yè)務(wù)組件引入這個jar包,有的使用正式版本,有的使用SNAPSHOT版本(正式版本上傳到倉庫必需要改版本,SNAPSHOT版本則不用),不管哪種版本,存在的問題就是,jar包的版本其實和代碼是關(guān)聯(lián)不上的,如果遇到問題需要看代碼時,我們只知道引入的是哪個版本,并不能看對應(yīng)版本的代碼(jar包的邏輯會隨著業(yè)務(wù)不斷的修改或者會新增內(nèi)容),對定位問題可能會有影響。項目是用gradle進行版本管理的,如果是maven的話可以同樣利用這個思路看下是否可行。
解決方案
上傳版本成功后,在當前的Commit上打一個tag,并push到遠程,前提條件是新加的代碼必須先commit或者push到遠程,為了避免這種情況,在上傳jar之前進行一個校驗,先push代碼才能上傳jar包。如果通過DevOps流水線從Git遠程拉的話,就不用加前置校驗,因為代碼已經(jīng)是最新的了。
tag的名字如果是正式版本就直接用版本名字當做tag名字,如果是SNAPSHOT那么就在后面加個時間戳。
代碼
uploadArchives {
repositories {
doFirst {
//寫的比較簡單粗暴,讀者可以考慮其他更優(yōu)雅的方式
if (artifactoryUser != null && artifactoryUser.length() != 0) {
def status = "git status".execute()
String gitStatus = status.inputStream.text
println gitStatus
if (gitStatus.contains("Changes not staged for commit") || gitStatus.contains("Changes to be committed")
|| gitStatus.contains("Your branch is ahead of")) {
throw new RuntimeException("請先提交代碼")
}
}
}
mavenDeployer {
repository(url: "http://central.xx.xxx.cn/artifactory/third-release-local") {
authentication(userName: xxxx, password: xxxxx)
}
snapshotRepository(url: "http://central.xxxx.cn/artifactory/third-snapshot-local") {
authentication(userName: xxxx, password: xxxxx)
}
}
doLast {
println "start tag"
String versionStr = version.toString()
String tagName = versionStr.contains("SNAPSHOT") ? versionStr + "-" + System.currentTimeMillis() : version
("git tag -a " + tagName + " -m \"upload archives auto tag\"").execute()
println "tag local success"
("git push origin " + tagName).execute()
println "tag push success"
}
}
}
效果

git_log.jpg

git_log_1.jpg
可能會遇到上傳成功,但是tag沒打成功,這種情況我覺得可以忽略,不用再花代價解決這種一致性問題,可以處理完打Tag失敗的,再重新上傳。
有人會說換個順序,先打Tag,再上傳Jar包,如果上傳成功無需做任何處理,如果上傳失敗,那么再把tag刪掉,也有可能刪Tag也出異常,如果打Tag代碼沒問題,出現(xiàn)失敗概率還是比較小,即使出現(xiàn)了再重試下。